IEnumerable的<>返回未设置为对象实例的对象引用

时间:2014-05-30 13:49:45

标签: c# ienumerable nullreferenceexception

我试图从界面获取值。我有这样的功能:

public IEnumerable<Car> CreateCars()
{
    IEnumerable<Car> carList = new List<Car>()
    {
        new Car{ Id = 1, Name = "Opel", CarProperties = { Color= "White", Model= "2012" }},
        new Car{ Id = 2, Name = "Citroen", CarProperties = { Color= "Blue", Model = "2014" }},
        new Car{ Id = 6, Name = "Peugeot", CarProperties = { Color= "Red", Model = "2013" } }
    };

    return carList;
}

当我调用该方法时,它会给出异常:

  

对象引用未设置为对象的实例。

我搜索但找不到答案。你能帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:4)

new Car{ Id = 1, Name = "Opel", CarProperties = { Color= "White", Model= "2012" }}

这一行等同于:

car = new Car();
car.Id = ...
car.Name = ...
car.CarProperties.Color = ...

您获得NullReferenceException这一事实让我相信car.CarProperties为空。

一种可能的解决方法是更改​​Car构造函数以初始化CarProperties属性或其支持字段。

public class Car
{
    public SomeType CarProperties {get; private set;}

    public Car()
    {
        CarProperties = new SomeType();
    }    
}

答案 1 :(得分:2)

我想这里引发了异常:

new Car{ Id = 1, Name = "Opel", CarProperties = { Color= "White", Model= "2012" }},

您应该使用相应的类型初始化CarProperties。类似的东西:

new Car { Id = 1, Name = "Opel", CarProperties = new CarProperty { Color= "White", Model= "2012" } },

您还可以在CarProperties类的构造函数中初始化Car属性。