我有这两个班级:
public class Parent
{
public int Id { get; set; }
public List<Child> Children { get; set; }
public Parent()
{
Children = new List<Child>();
}
}
public class Child
{
public int Id { get; set; }
public int ParentId { get; set; }
}
是否可以做这样的事情:
var parent = new Parent()
{
Id = 1,
Children = new List<Child>()
{
new Child()
{
Id = 100,
ParentId = parent.Id
}
}
};
答案 0 :(得分:3)
我不这么认为。为什么不简单地将父ID提取到变量?
var parentId = 1;
var parent = new Parent()
{
Id = parentId,
Children = new List<Child>()
{
new Child()
{
Id = 100,
ParentId = parentId
}
}
};