C#中的数组在引用类型上隐式为协变的:
object[] listString = new string[] { "string1", "string2" };
但不是值类型,因此如果更改string为int,将得到编译错误:
object[] listInt = new int[] {0, 1}; // compile error
现在,您需要担心的是,当您int像以下两种语法那样声明数组时,它们下面没有显式声明类型int,仅在上进行区分new[],编译器将以不同的方式对待:
object[] list1 = { 0, 1 }; //compile successfully
object[] list2 = new[] {0, 1}; //compile error
您将object[] list1 = { 0, 1 };成功编译,但是object[] list2= new[] {0, 1};编译错误。
看来C#编译器对待
object[] list1 = { 0, 1 };
如
object[] list1 = new object[]{ 0, 1 };
但
object[] list2 = new[] { 0, 1 };
如
object[] list2 = new int[]{ 0, 1 }; //error because of co-variant
在这种情况下,为什么C#编译器的行为方式不同?