我试图从界面获取值。我有这样的功能:
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;
}
当我调用该方法时,它会给出异常:
对象引用未设置为对象的实例。
我搜索但找不到答案。你能帮我解决这个问题吗?
答案 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
属性。