【发布时间】:2011-06-21 10:07:03
【问题描述】:
如您所知,列表中不允许使用数组初始化语法。它会给出一个编译时错误。示例:
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 test= new Test { Field = { 1, 2, 3 }};具有相同的行为。 -
“对象引用未设置为对象”非常合乎逻辑,因为您的列表字段未初始化。将测试主体更改为 public List
Field = new List ();使这个运行也没有任何问题。 -
拿个反射器,看看编译器是怎么处理的,你就明白了。还要看看 var stuff = new List
() {4,5};被处理
标签: c# compiler-errors