从对象初始化访问属性 [英] Accessing properties from object initializer
本文介绍了从对象初始化访问属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有如下的人
类
class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName
{
get { return FirstName + " " + LastName; }
}
public IEnumerable<Person> Children { get; set; }
}
我可以初始化它是这样的:
I could initialize it like this:
Person p = new Person() { FirstName = "John", LastName = "Doe" };
但有可能引用人
的另一个属性的对象初始化,所以我可以做的,例如这样的事情?
But is it possible to reference another property of Person
in the object initializer, so I could do for example something like this?
Person p = new Person()
{
FirstName = "John",
LastName = "Doe",
Children = GetChildrenByFullName(FullName);
};
修改
为了这个问题,所引用的属性没有根据其他属性来计算,但它的价值可能在构造函数中进行设置。
For the sake of the question, the referenced property doesn't have to be calculated according to other properties, but its value could be set in the constructor.
感谢
推荐答案
可以这样做:
void Foo()
{
String FullName = "";
Person p = new Person()
{
FirstName = "John",
LastName = "Doe",
Children = GetChildrenByFullName(FullName); // is this p.FullName
// or local variable FullName?
};
}
这篇关于从对象初始化访问属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文