如您所知,不允许对列表使用数组初始化语法。它会给出一个编译时错误。示例:
List<int> test = { 1, 2, 3}
// At compilation the following error is shown:
// Can only use array initializer expressions to assign to array types.
但是今天我做了以下事情(非常简单):
class Test
{
public List<int> Field;
}
List<Test> list = new List<Test>
{
new Test { Field = { 1, 2, 3 } }
};
上面的代码编译得很好,但运行时会出现“对象引用未设置为对象”的运行时错误。
我希望该代码会产生编译时错误。我要问你的问题是:为什么不能,这种情况何时会正确运行是否有任何充分的理由?
这已经使用 .NET 3.5(包括 .Net 和 Mono 编译器)进行了测试。
干杯。
最佳答案
我认为这是设计使然的行为。 Test = { 1, 2, 3 }
被编译成调用 Add
的代码Test
中存储列表的方法 field 。
你得到 NullReferenceException
的原因是那个Test
是null
.如果你初始化 Test
字段到一个新列表,然后代码将工作:
class Test {
public List<int> Field = new List<int>();
}
// Calls 'Add' method three times to add items to 'Field' list
var t = new Test { Field = { 1, 2, 3 } };
这很符合逻辑——如果你写 new List<int> { ... }
然后它创建一个新的列表实例。如果您不添加对象构造,它将使用现有实例(或 null
)。据我所知,C# 规范不包含任何与这种情况匹配的显式转换规则,但它给出了一个示例(参见第 7.6.10.3 节):
A List<Contact>
可以按如下方式创建和初始化:
var contacts = new List<Contact> {
new Contact {
Name = "Chris Smith",
PhoneNumbers = { "206-555-0101", "425-882-8080" }
},
new Contact {
Name = "Bob Harris",
PhoneNumbers = { "650-555-0199" }
}
};
与效果相同
var contacts = new List<Contact>();
Contact __c1 = new Contact();
__c1.Name = "Chris Smith";
__c1.PhoneNumbers.Add("206-555-0101");
__c1.PhoneNumbers.Add("425-882-8080");
contacts.Add(__c1);
Contact __c2 = new Contact();
__c2.Name = "Bob Harris";
__c2.PhoneNumbers.Add("650-555-0199");
contacts.Add(__c2);
哪里 __c1
和 __c2
是临时变量,否则不可见且不可访问。
关于c# - List<int> test = {1, 2, 3} - 它是功能还是错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24020741/