首页 > 解决方案 > 主/从关系的对象初始化

问题描述

我有两个表示主从关系的类,其中主对象包含详细信息,而详细对象引用主对象。我正在尝试使用对象初始化来实例化它们,但不确定如何将主引用传递给细节......也许不可能,但想问一下。

我有以下课程:

public class Detail
{
    public Detail(string type, string value, Entity entity) {...}
    public string Value { get; set; }

    public Master Master { get; set; }
}

public class Master
{
    public string ID { get; set; }

    public IEnumerable<Detail> Details{ get; set; }
}

如果我想使用对象初始值设定项,如何将主引用传递到详细实例?

List<Master> = new List<Master>()
{
    new Master()
    {
        Details= new List<Detail>()
        {
             new Detail()
             {
                 Master = ???
             } 
        }
    }
};

标签: c#object-initializers

解决方案


忽略您的代码充满错误的事实,您不能使用对象初始化来引用父图的部分。您要么需要使用构造函数、助手、设置器,要么在事后设置它:

public class Master()
{
     public Master(List<Detail> details)
     {
         details.ForEach(x => x.Master = this);
         Details = details;
     }
     ...
}

用法:

List<Master> = new List<Master>()
{
    new Master(new List<details>{...})
}

或事后的例子,因为DetailsIEnumerable<T>

list.ForEach(x => x.Details.ToList().ForEach(y => y.Master = x));

推荐阅读