对象初始化器中的属性可以互相引用吗? [英] Can properties inside an object initializer reference each other?

查看:117
本文介绍了对象初始化器中的属性可以互相引用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在创建动态对象匿名类型的对象(即对象初始化器内部)的过程中,属性是否可以相互引用?我下面的简化示例需要重用Age属性,而无需再次调用GetAgeFromSomewhere().当然,这是行不通的.关于如何做到这一点有什么建议吗?

Is it somehow possible for properties to reference each other during the creation of a dynamic object an anonymously-typed object (i.e. inside the object initializer)? My simplified example below needs to reuse the Age property without making a second heavy call to GetAgeFromSomewhere(). Of course it doesn't work. Any suggestion on how to accomplish this?

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

使用动态对象匿名类型的对象初始值设定项,这种可能性是否可行?

Is something like this possible or not possible with dynamic objects anonymously-typed object initializers?

推荐答案

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

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
};

这篇关于对象初始化器中的属性可以互相引用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆