从对象初始化访问属性初始化、属性、对象

由网友(怪人i)分享简介:我有如下的人类class Person{public string FirstName { get; set; }public string LastName { get; set; }public string FullName{get { return FirstName + " " + LastName; }...

我有如下的

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?
  };
}
阅读全文

相关推荐

最新文章