Dav*_*kle 5 c# compiler-errors
考虑以下两个程序.第一个程序在编译时因编译器错误而失败:
using System.Collections.Generic;
class Program {
static void Main(string[] args) {
List<int> bar = { 0, 1, 2, 3 }; //CS0622
}
}
Run Code Online (Sandbox Code Playgroud)
只能使用数组初始值设定项表达式分配给数组类型.请尝试使用新表达式.
这个我完全明白. 当然,解决方法是使用new[] {...}数组初始化程序语法,程序将编译并正确运行.
现在考虑第二个程序,只是略有不同:
using System.Collections.Generic;
public class Foo {
public IList<int> Bar { get; set; }
}
class Program {
static void Main(string[] args) {
Foo f = new Foo { Bar = { 0, 1, 2, 3 } }; //Fails at run time
}
}
Run Code Online (Sandbox Code Playgroud)
这个程序编译.而且,生成的运行时错误是:
你调用的对象是空的.
这对我很有意思.为什么第二个程序甚至会编译?我甚至尝试制作Bar一个实例变量而不是属性,认为这可能与奇怪的行为有关.它不是.与第一个示例一样,使用new[] {...}数组初始化程序语法会使程序正常运行而不会出现错误.
在我看来,第二个程序不应该编译.这是问题所在. 为什么呢? 这是什么我在这里没有掌握?
(编译器:Visual Studio 2012,Framework:.NET 4.5.1)
| 归档时间: |
|
| 查看次数: |
71 次 |
| 最近记录: |