列表<int>test = {1, 2, 3} - 这是一个特性还是一个错误? [英] List<int> test = {1, 2, 3} - is it a feature or a bug?
问题描述
如您所知,不允许在列表中使用数组初始化语法.它会给出编译时错误.示例:
As you know, it is not allowed to use the Array-initialisation syntax with Lists. It will give a compile-time error. Example:
List<int> test = { 1, 2, 3}
// At compilation the following error is shown:
// Can only use array initializer expressions to assign to array types.
不过今天我做了以下(非常简化):
However today I did the following (very simplified):
class Test
{
public List<int> Field;
}
List<Test> list = new List<Test>
{
new Test { Field = { 1, 2, 3 } }
};
上面的代码编译得很好,但运行时会出现对象引用未设置为对象"的运行时错误.
The code above compiles just fine, but when run it will give a "Object references is not set to an object" run-time error.
我希望该代码会出现编译时错误.我要问你的问题是:为什么不呢?这种场景何时可以正确运行,有什么好的理由吗?
I would expect that code to give a compile-time error. My question to you is: Why doesn't it, and are there any good reasons for when such a scenario would run correctly?
这已经使用 .NET 3.5 进行了测试,包括 .Net 和 Mono 编译器.
This has been tested using .NET 3.5, both .Net and Mono compilers.
干杯.
推荐答案
我认为这是一种设计行为.Test = { 1, 2, 3 }
被编译成代码,该代码调用存储在 Test
字段中的列表的 Add
方法.
I think this is a by-design behavior. The Test = { 1, 2, 3 }
is compiled into code that calls Add
method of the list stored in the Test
field.
您得到 NullReferenceException
的原因是 Test
是 null
.如果您将 Test
字段初始化为新列表,则代码将起作用:
The reason why you're getting NullReferenceException
is that Test
is null
. If you initialize the Test
field to a new list, then the code will work:
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
然后它创建一个新的列表实例.如果不添加对象构造,它将使用现有实例(或 null
).据我所知,C# 规范不包含任何与此场景匹配的显式翻译规则,但它提供了一个示例(请参阅第 7.6.10.3 节):
It is quite logical - if you write new List<int> { ... }
then it creates a new instance of list. If you don't add object construction, it will use the existing instance (or null
). As far as I can see, the C# spec doesn't contain any explicit translation rule that would match this scenario, but it gives an example (see Section 7.6.10.3):
一个List
可以被创建和初始化如下:
A List<Contact>
can be created and initialized as follows:
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
是临时变量,否则不可见和无法访问.
where __c1
and __c2
are temporary variables that are otherwise invisible and inaccessible.
这篇关于列表<int>test = {1, 2, 3} - 这是一个特性还是一个错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!