检查下面的代码。在这里,我想设置Root
类的值及其所有子列表值。我已经像波纹管一样尝试过了,但是我可以用Root
来做到这一点,但是如何为所有子类设置值呢?
模型类别:
namespace MyProject.ViewModels
{
public class Child3
{
public int Id { get; set; }
public string text { get; set; }
}
public class Child2
{
public int Id { get; set; }
public string text { get; set; }
public List<Child3> children { get; set; }
}
public class Child
{
public int Id { get; set; }
public string text { get; set; }
public List<Child2> children { get; set; }
}
public class Root
{
public int Id { get; set; }
public string text { get; set; }
public List<Child> children { get; set; }
}
}
试图设置值:
var root = new List<Root>();
root.Add(new Root
{
Id = 1,
text = "foo",
children = new List<Child>()
{
//i am not getting idea from here.
},
});
尝试一下
var root = new List<Root>();
root.Add(new Root
{
Id = 1,
text = "foo",
children = new List<Child>()
{
new Child
{...},
new Child
{...},
new Child
{...}
},
});
[被卡住的地方应该有一堆Child
ren,所以创建一堆Child
对象!
children = new List<Child>
{
new Child {
...
},
new Child {
...
},
...
}
在每个Child
对象内部,您可以在以下位置继续使用模式:
new Child {
Id = ...,
Text = ...,
children = new List<Child2> {
new Child2 { ... },
new Child2 { ... },
...
}
}
您应该充分利用C#的object and collection initializers。
首先,请考虑更新模型以自动实例化其列表。例如:
public class Root
{
public int Id { get; set; }
public string text { get; set; }
public List<Child> children { get; set; } = new List<Child>();
}
请注意,children
属性用一个空列表初始化。现在,您可以轻松地在对象初始化代码中指定收集项。
var root = new List<Root>
{
new Root
{
Id = 1,
text = "foo",
children =
{
new Child
{
// ...
},
new Child
{
// ...
},
}
}
};
如果您不想自动实例化集合,则需要在每个级别上实例化它们:
var root = new List<Root>
{
new Root
{
Id = 1,
text = "foo",
children = new List<Child>
{
new Child
{
// ...
},
new Child
{
// ...
},
}
}
};
var root = new List<Root>();
root.Add(new Root
{
Id = 1,
text = "foo",
children = new List<Child>()
{
new Child{
Id = 1,
text = "child text",
children = new List<Child2>(){
new Child2{
Id = 1,
text = "child text",
children = new List<Child3>{
new Child3{
Id =1,
text = "child text"
},
new Child3{
Id =2,
text = "child text"
}
}
},
new Child2{
Id = 2,
text = "child text",
children = new List<Child3>{
new Child3{
Id =3,
text = "child text"
},
new Child3{
Id =4,
text = "child text"
}
}
}
}
},
//Child 2
new Child{
Id = 1,
text = "child text",
children = new List<Child2>(){
new Child2{
Id = 1,
text = "child text",
children = new List<Child3>{
new Child3{
Id =1,
text = "child text"
},
new Child3{
Id =2,
text = "child text"
}
}
},
new Child2{
Id = 2,
text = "child text",
children = new List<Child3>{
new Child3{
Id =3,
text = "child text"
},
new Child3{
Id =4,
text = "child text"
}
}
}
}
}
},
});