[英]How does this compile? c#
object obj = new object[] { new object(), new object() };
這是如何編譯的? 這似乎令人困惑。
似乎它應該是
object[] obj = new object[] { new object(), new object() };
要么
object[] obj = { new object(), new object() };
對象是一切的基礎。 可以將任何內容分配給object類型的變量。
它編譯是因為“對象”可以是任何東西,因此它可以是對象數組的引用。 下面的代碼使用字符串來區分更清晰,可能會有所幫助。 所以:
List<string> myStrings = new List<string>() { "aa", "bb" };
// Now we have an array of strings, albeit an empty one
string[] myStringsArray = myStrings.ToArray();
// Still a reference to myStringsArray, just held in the form of an object
object stillMyStringsArray = (object)myStringsArray;
// Get another array of strings and hold in the form of an object
string[] anotherArray = myStrings.ToArray();
object anotherArrayAsObject = (object)anotherArray;
// Store both our objects in an array of object, in the form of an object
object myStringArrays = new object[] { stillMyStringsArray, anotherArrayAsObject };
// Convert myStringArrays object back to an array of object and take the first item in the array
object myOriginalStringsArrayAsObject = ((object[])myStringArrays)[0];
// Conver that first array item back into an array of strings
string[] myOriginalStringsArray = (string[])myOriginalStringsArrayAsObject;
本質上,對象始終可以是對任何東西的引用,甚至是對象數組。 對象並不關心放在其中的內容,因此在代碼的最后,我們有一個字符串數組。 在Visual Studio中運行該代碼,刪除幾個斷點並跟進。 它有望幫助您理解為什么您指定的代碼有效=)
在
object obj = new object[] { ...}
右手部分確實產生了類型為object[]
的引用,但該類型與任何其他類型一樣,與object
分配兼容。
object obj = ...這里可以指集合。 這並不是說'對象'的不同用法是指同一類型的對象。
對象數組是一個對象,但這確實很奇怪。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.