0

我有一堂课

public class Person
{
    public string Name{ get; set; }
    public string Address{ get; set; }
    public List<Person> Children{ get; set; }
}

在这里,我有一个属性儿童列表。

现在我正在使用类型初始化器创建此类实例的数组

var persons = new []{
    new Person{ Name="Some Name", Address = "Some Address" },
    new Person{ Name="Some Name 2", Address = "Some Address 2", Children = new List<Person>{
          new Person { Name = "Some Name 3",
                ** Address = <here I want its parent Address>  "Some Address 2" **}
       }
    }
};

所以,我的问题是我正在创建一个 Person 的对象,我在其中分配了它的 Address 属性,现在我希望这个属性值分配它的子级,但是我没有找到一种方法来获取它的父级,就像我们通过这个关键字所做的那样在其定义中获取类成员。

4

1 回答 1

1

C# 没有提供简单的方法来做到这一点。Person上述对象与其子对象之间的父子关系不是由语言强制或提供的。解决上述问题的最简单方法是将地址存储在变量中并引用它。

string address = "Some Address 2";
var persons = new []{
    new Person{ Name="Some Name", Address = "Some Address" },
    new Person{ Name="Some Name 2", Address = address, 
        Children = new List<Person>{
              new Person { Name = "Some Name 3", address }
       }
    }
};

Alternatively, a Person object could set the address of any children to itself in a data-binding like arrangement.

于 2012-09-17T11:54:37.887 回答