您可以通过多种方式初始化列表和嵌套列表。想象这是我的课。我已经包含了一个用于对象初始值设定项模式的无参数构造函数(尽管它不限于无参数构造函数),一个带有名称和列表对象的构造函数,以及一个带有名称和 params 数组的构造函数节点数。
为了简单起见,我自己做了类引用,但显然你不需要这样做。
public class Node
{
public Node() // you could pass nothing and set them manually or use the object initializer pattern
{
}
public Node(string name, List<Node> nodes) // you could pass the name and an existing list
{
this.Name = name;
this.Nodes = nodes;
}
public Node(string name, params Node[] nodes) // you could pass the name and a list of items (which can be called like Node("a", node, node, node)
{
this.Name = name;
this.Nodes = nodes.ToList(); // needs using System.Linq; at the top of the file or namespace
}
public string Name { get; set; }
public List<Node> Nodes { get; set; }
}
例子:
// object initializer
var childChildChildChildNode = new Node
{
Name = "ChildChildChildChild"
}
// constructor: string name, params Node[] nodes
var childChildChildNode = new Node("ChildChildChild", childChildChildChildNode);
// constructor: string name, List<Node> nodes
var childChildNode = new Node("ChildChild", new List<Node> { childChildChildNode });
// object initializer
var childNode = new Node
{
Name = "Child",
Nodes = new List<Node>()
};
// add items to the list of the child node
childNode.Nodes.Add(childChildNode);
// object initializer for node and list
var parentNode = new Node
{
Name = "Parent",
Nodes = new List<Node> { childNode }
};
// full object initializer
var otherParentNode = new Node
{
Name = "Parent",
Nodes = new List<Node>
{
new Node {
Name = "Child",
Nodes = new List<Node>
{
new Node
{
Name = "ChildChild1"
},
new Node
{
Name = "ChildChild2"
}
}
}
}
};
请注意,这并不是使用数组和嵌套数组初始化对象的方法的详尽列表,只是一些示例来帮助您入门。