且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

对象初始化器中的属性可以互相引用吗?

更新时间:2023-11-08 11:57:34

不幸的是,即使使用显式类型的对象,这也是不可能的.这是因为对象初始化程序的工作方式.例如:

Unfortunately it's not possible, even with explicitly typed objects. This is because of the way object initializers work. For example:

public class MyClass
{
    public int Age = 10;
    public bool IsLegal = Age > 18;
}

在"IsLegal"处产生此编译器错误:

Yields this compiler error at "IsLegal":

错误1字段初始化程序无法引用非静态字段, 方法或属性"MyClass.Age" ...

Error 1 A field initializer cannot reference the non-static field, method, or property 'MyClass.Age' ...

字段初始化程序不能引用其他非静态字段,并且由于匿名类型不能创建静态字段,因此您不能使用一个字段的值来初始化另一个字段.解决此问题的唯一方法是,在匿名类型之外声明变量,并在初始化程序中使用它们.

Field initializer can't reference other non-static fields, and since anonymous types don't create static fields, you can't use the value of one field to initialize another. The only way around this, is to declare the variables outside the anonymous type and use them inside the initializer.

int age = GetAgeFromSomewhere(id);
var profile = new {
  Age = age,
  IsLegal = age > 18
};