object obj = new object[] { new object(), new object() };
How does this compile? It seems confusing.
Seems it should either be 开发者_Go百科
object[] obj = new object[] { new object(), new object() };
or
object[] obj = { new object(), new object() };
object is the base for everything. Anything can be assigned to a variable of type object.
It compiles because an "object" can be anything, therefore it can be a reference to an array of object. The code below using strings to make the distinction a little clearer, might help. So:
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;
Essentially, an object can always be a reference to anything, even an array of object. Object doesn't care what is put in it, so by the very end of the code there, we've got a string array back. Run that code up in Visual Studio, drop a few breakpoints in and follow it through. It'll hopefully help you make sense of why the code you specified is valid =)
In
object obj = new object[] { ...}
The right hand part does yield a reference of type object[]
but that type, like any other type, is assignment-compatible with object
.
object obj = ... here may refer to a Collection. It's not said that the difference usage of 'object' here refers to the same type of object.
An array of objects is an object, but this is indeed weird.
精彩评论