NullReferenceException
我在以下代码中遇到运行时异常:
public class Container
{
public IList<string> Items { get; set; }
}
class Program
{
static void Main(string[] args)
{
var container = new Container() { Items = {"Test"} };
}
}
编译器无法创建接口实例是合乎逻辑的,但我遇到了运行时异常,而不是编译时间。当我进一步调查这种行为时,我更加困惑:
var container = new Container() { Items = {} }; //Legal, Items is null after initialization
var container = new Container() { Items = { "Test" } }; //Legal, throws exception
container.Items = {}; //Illegal doesn't compile
container.Items = {"Test"}; //Illegal doesn't compile
这是某种错误还是我不明白?我正在使用.net framework 4.0