我有以下情况:
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中的导航属性。
答案 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
,您可以使用子级中的父级:
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);
}