C# · 12月 29, 2021

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 };



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 (§ of the set of
expressions in the array initializer.节如下所示:

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


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.