如您所知,不允许将Array-initialisation语法与Lists一起使用.它会产生编译时错误.例:
List<int> test = { 1, 2, 3}
// At compilation the following error is shown:
// Can only use array initializer expressions to assign to array types.
Run Code Online (Sandbox Code Playgroud)
但是今天我做了以下(非常简化):
class Test
{
public List<int> Field;
}
List<Test> list = new List<Test>
{
new Test { Field = { 1, 2, 3 } }
};
Run Code Online (Sandbox Code Playgroud)
上面的代码编译得很好,但是在运行时它会给出"对象引用未设置为对象"运行时错误.
我希望该代码能够产生编译时错误.我的问题是:为什么不是,并且有什么好的理由可以让这种情况正确运行?
这已经使用.NET 3.5进行了测试,包括.Net和Mono编译器.
干杯.