C#类中的父子关系

时间:2017-12-06 11:53:56

标签: c#

我有以下情况:

public class ParentObject
{
public int id {get;set;}
public string parent_object_name {get;set;}
public List<ChildObject> child_objects {get;set;}
}

public class ChildObject
{
public int id {get;set;}
public string child_object_name {get;set;}
}

ParentObject parent_object = new ParentObject()
{
  id = 1,
  parent_object_name = "test name",
  child_objects = new List<ChildObject>(){ new ChildObject(){ id = 1, child_object_name = "test name"};
}

我知道引用parent_object.child_objects是完全有效的,但我不知道如何编写我的类以获得child_objects.First().parent_object等引用。类似于Entity Framework中的导航属性。

3 个答案:

答案 0 :(得分:3)

一种方法是定义一个接受父作为参数的构造函数。

public class ChildObject
{
  public ChildObject(ParentObject aParent)
  {
    parent = aParent
  }

  public ParentObject parent { get; private set; }
  public int id {get;set;}
  public string child_object_name {get;set;}
}

答案 1 :(得分:2)

试试这个:

public class ChildObject
{
    public int id { get; set; }
    public string child_object_name { get; set; }
    public ParentObject parent_object { get; set; }
}

答案 2 :(得分:1)

通过在ParentObject中添加ChildObject,您可以使用子级中的父级:

Try it online

public class ParentObject
{
    public int id {get;set;}
    public string parent_object_name {get;set;}
    public List<ChildObject> child_objects {get;set;}
}

public class ChildObject
{
    public int id {get;set;}
    public string child_object_name {get;set;}

    // add a parent
    public ParentObject parent_object {get;set;}
}


public static void Main()
{
    var parent_object = new ParentObject
    {
        id = 1,
        parent_object_name = "test name"
    };
    parent_object.child_objects = new List<ChildObject>
    {
        new ChildObject {id = 1, child_object_name = "test name", parent_object = parent_object}
    };
    Console.WriteLine(parent_object.child_objects.First().parent_object.parent_object_name);
}