这是如何编译的? C#
发布时间:2020-12-16 00:13:00 所属栏目:百科 来源:网络整理
导读:object obj = new object[] { new object(),new object() }; 这是如何编译的?这似乎令人困惑. 似乎它应该是 object[] obj = new object[] { new object(),new object() }; 要么 object[] obj = { new object(),new object() }; 解决方法 它编译是因为“对象
object obj = new object[] { new object(),new object() }; 这是如何编译的?这似乎令人困惑. 似乎它应该是 object[] obj = new object[] { new object(),new object() }; 要么 object[] obj = { new object(),new 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中运行该代码,删除几个断点并跟进.它有望帮助您理解为什么您指定的代码有效=) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |