陣列在C#是共變隱式上引用類型:爲什麼C#表現不同的兩個int數組語法
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#編譯器在這種情況下的行爲方式不同?
+1,你來自[這個問題](http://stackoverflow.com/q/16456507/961113) – Habib 2013-05-09 08:03:29
@Habib:是的,從中得到啓發 – 2013-05-09 08:04:16
快速猜測,所有的引用類型都採用相同的數字字節爲了便於參考,它易於隱含轉換。 – Jodrell 2013-05-09 08:21:12