C#类中的父子关系

C#类中的父子关系,c#,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 {g

我有以下情况:

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"};
}
公共类ParentObject
{
公共int id{get;set;}
公共字符串父对象名称{get;set;}
公共列表子对象{get;set;}
}
公共类子对象
{
公共int id{get;set;}
公共字符串子对象名称{get;set;}
}
ParentObject parent_object=新ParentObject()
{
id=1,
父对象名称=“测试名称”,
child_objects=new List(){new ChildObject(){id=1,child_object_name=“test name”};
}
我知道引用
parent\u object.child\u objects
是完全有效的,但我不确定如何对我的类进行编码,使其具有引用,例如
child\u objects.First().parent\u object
,即类似于实体框架中的导航属性。

尝试以下操作:

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

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

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

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

公共类ParentObject
{
公共int id{get;set;}
公共字符串父对象名称{get;set;}
公共列表子对象{get;set;}
}
公共类子对象
{
公共int id{get;set;}
公共字符串子对象名称{get;set;}
//添加父项
公共ParentObject parent_对象{get;set;}
}
公共静态void Main()
{
var parent_object=新的ParentObject
{
id=1,
父对象名称=“测试名称”
};
父对象。子对象=新列表
{
新的ChildObject{id=1,child\u object\u name=“test name”,parent\u object=parent\u object}
};
Console.WriteLine(父对象。子对象。First()。父对象。父对象。\u名称);
}

@Fildor已编辑。是否建议使用WeakReference?@Fildor-为什么?出于什么目的?你认为父母可能接受GCD,但孩子不应该接受GCD?这是我的想法,是的。但我不确定是否有必要。现在我读了你的评论,这甚至可能是个坏主意。
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);
}