c# - 主/从关系的对象初始化
问题描述
我有两个表示主从关系的类,其中主对象包含详细信息,而详细对象引用主对象。我正在尝试使用对象初始化来实例化它们,但不确定如何将主引用传递给细节......也许不可能,但想问一下。
我有以下课程:
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 = ???
}
}
}
};
解决方案
忽略您的代码充满错误的事实,您不能使用对象初始化来引用父图的部分。您要么需要使用构造函数、助手、设置器,要么在事后设置它:
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>{...})
}
或事后的例子,因为Details
是IEnumerable<T>
:
list.ForEach(x => x.Details.ToList().ForEach(y => y.Master = x));
推荐阅读
- wordpress - 在 wordpress 中包含一个类
- elasticsearch - 包含整数数组的 ElasticSearch 嵌套对象
- flutter - 如何在颜色名称旁边显示颜色预览?
- regex - Kibana 弹性搜索正则表达式字符串长度
- java - 我需要为此使用实例变量吗?
- android - 如何解决 Android 支持库和 AndroidX 之间的冲突?
- c - 在 System() 调用后打印时 printf 出现意外行为
- powershell - 使用另一个数组中的元素从一个数组中删除元素(关闭)
- android - Flutter 应用程序仅在发布模式下崩溃
- android - 更改新 MaterialDatePicker 中的按钮文本