这是我的代码:
var Operations = new List<Operation>
{
new Operation
{
Date = DateTime.Now,
OperationId = 0,
OperationType = OperationType.Entry,
OperationVehicles = new List<OperationVehicle>
{
new OperationVehicle { Vehicle = vehicle},
}
},
new Operation
{
Date = DateTime.Now.AddDays(2),
OperationId = 1,
OperationType = OperationType.Exit,
OperationVehicles = new List<OperationVehicle>
{
new OperationVehicle { Vehicle = vehicle, /* Operation = ???*/},
}
}
};
OperationVehicle
类有一个 Operation
类型的虚拟公共(public)属性,我想在这个阶段用它的父 Operation 实例实例化它。好吧,我认为此时操作可能尚未创建。有没有办法在 C# 中执行此操作,还是我必须做经典的矫揉造作?
最佳答案
来自 C# Language spec 中的第 7.6.10.2 节(强调我的)。
An object initializer consists of a sequence of member initializers, enclosed by { and } tokens and separated by commas. Each member initializer must name an accessible field or property of the object being initialized, followed by an equals sign and an expression or an object initializer or collection initializer. It is an error for an object initializer to include more than one member initializer for the same field or property. It is not possible for the object initializer to refer to the newly created object it is initializing.
如果我正确理解了您的问题,那么就不可能在对象初始化中引用新对象,因此无法执行您正在尝试的操作,因为此时 vehicle
不可访问。
关于c# - 如何在声明时使用其父实例实例化属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17903717/