C# · 12月 29, 2021

c# – 实现接口的数组的隐式类型

我的印象是,C#编译器将隐式地键入一个类型,它们都可以隐式转换为一个数组.

编译器生成
没有找到隐式类型数组的最佳类型

public interface ISomething {}public interface ISomething2 {}public interface ISomething3 {}public class Foo : ISomething { }public class Bar : ISomething,ISomething2 { }public class Car : ISomething,ISomething3 { }void Main(){ var obj1 = new Foo(); var obj2 = new Bar(); var obj3 = new Car(); var objects= new [] { obj1,obj2,obj3 };}

我知道纠正这个的方法是声明类型如下:

new ISomething [] { obj1,…}

但是我在这里的封面类型帮助之下.

解决方法 C#编译器考虑所有指定元素的一组类型.它不考虑常见的基本类型等

您可以转换其中一个表达式:

var objects= new [] { obj1,(ISomething) obj3 };

…但是个人我只是使用明确的形式:

var objects= new ISomething[] { obj1,obj3 };

或者,如果您明确声明obj1,obj2和obj3作为ISomething类型的任何或全部,那么在不更改数组初始化表达式的情况下也可以正常工作.

从C#3规范,第7.5.10.4节:

An array creation expression of the
third form is referred to as an
implicitly typed array creation
expression. It is similar to the
second form,except that the element
type of the array is not explicitly
given,but determined as the best
common type (§7.4.2.13) of the set of
expressions in the array initializer.

7.4.2.13节如下所示:

In some cases,a common type needs to
be inferred for a set of expressions.
In particular,the element types of
implicitly typed arrays and the return
types of anonymous functions with
block bodies are found in this way.
Intuitively,given a set of
expressions E1…Em this inference
should be equivalent to calling a
method

06002

with the Ei as arguments. More precisely,the inference starts out with an unfixed type variable X. Output type inferences are then made from each Ei with type X. Finally,X is fixed and the resulting type S is the resulting common type for the expressions.