简体   繁体   中英

Assign a children value same as its parent value in type initializer

I have a class Like

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

Here I have a property Children List.

and Now I am creating an array of this class instances by using type initializer like

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

So, My Problem is that I am creating an object of Person where I assign its Address property and now I want this property value to assign its children, but I am not finding a way to get the its parent like we just do by this keyword to get a class member in its definition.

There is no easy way provided by C# to do this. The parent-child relationship between the Person object and its children above is not enforced or provided by the language. The easiest way to solve the problem above is store the address in a variable and reference it.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM