c# - 如何在声明时使用其父实例实例化属性

标签 c# class instance

这是我的代码:

 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/

相关文章:

c# - 是否有等同于 VS C# 10 on VS 08 的 CTRL+D, E?

c++ - 如何将 WndProc 用作类函数

ruby - 如何拒绝在 Ruby 中创建实例变量

c# - 实例化包含 static void Main() 的类

c# - 如何通过反射获取类中某个属性的 "class type"?

c# - 在 ASP .NET MVC 应用程序中创建用户角色时出现错误

c# - 我们可以在 C# 中使用来自另一个 winform 的一些 winform 面板吗?

class - OWL 不同类的相同对象属性

c# - 使用数组语法初始化我的类

haskell - 如何在不推导的情况下实例化 Eq