Can someone explain how the compiler proceeds here to find the "common" type (double).
I assume the IConvertible plays a role here?
private static void Main(string[] args)
{
var nrColl = new[] { 1, 2, 0.14, 'a',};
}
Can someone explain how the compiler proceeds here to find the "common" type (double).
I assume the IConvertible plays a role here?
private static void Main(string[] args)
{
var nrColl = new[] { 1, 2, 0.14, 'a',};
}
请参阅说明书中的Finding the best common type of a set of expressions.
- 引入了一种新的非固定型变量X.
- 对于每个表达式Ei,从它到X执行输出类型推断.
- 如果可能,X是固定的,并且结果类型是最好的公共类型.
- 否则,推理就会失败.
直观地说,这个推断等同于调用一个方法VOID M(X x₁...X xᵥ),以Eᵢ为自变量,推断X.
如果您遵循如何完成输出类型推断的步骤,您最终会看到,在本例中,类型变量X
将具有下限int
、double
和char
.
然后,到fix个X
,
对于Xᵢ的每个下界U,从候选集合中移除不存在从U到U的隐式转换的所有类型Uₑ.
如果在剩余的候选类型Uₑ中存在从所有其他候选类型隐式转换到的唯一类型V,则Xᵢ固定为V.
我们可以try 手动操作.
让我们先来看看int
个.int
可以隐式转换为double
,因此double
不会被删除.无法将int
转换为char
,因此删除了char
.接下来我们来看一下double
.double
不能隐式转换为int
,因此将删除int
.我们现在只剩下double
,所以X
固定为double
.
基本上,如果数组初始化器中的表达式类型中恰好有一个类型T
,所有其他表达式都可以隐式转换为该类型,则T
是数组的类型.