为了提供更合理的构造函数,我们不得不进行多次构造函数的重载,使得用户的调用更加简单。但是这样的排列组合随着参数的增加成几何级增长,的确很不方便。现在有了Object and Collection Initializer(对象和集合初始化器)就方便多了。
举个例子:
private class Cat { // Auto-implemented properties. public int Age { get; set; } public string Name { get; set; } }
Cat cat = new Cat { Age = 10, Name = "Fluffy" };List<Cat> cats = new List<Cat> { new Cat(){ Name = "Sylvester", Age=8 }, new Cat(){ Name = "Whiskers", Age=2 }, new Cat(){ Name = "Sasha", Age=14 } };好了,常识性的普及就到这里。现在让我讲讲一些特殊的。
- 如何初始化仅含有get的collection?
public class MyClass { public MyClass() { MyCollection = new List<string>(); } public List<string> MyCollection { get; private set; } }
正确的方式是:
MyClass test = new MyClass() { MyCollection = { "AAA", "BBB", "CCC" } };
- 如何初始化Dictionary collection?
public class MyClass
{
public Dictionary<int, string> MyDictionary { get; set; }
}
正确的方法是:
MyClass test = new MyClass()
{
MyDictionary = new Dictionary<int, string>()
{
{1, "AAA"},
{2, "BBB"},
{3, "CCC"}
}
};
- 什么时候使用Nested的Initializer?
一开始觉得写Nested的Initializer,代码不太好读。现在发现的树形结构里使用Nested的Initializer能够把树的结构给表现得比较清楚。所以推荐大家也试试看。举个WF 4.0的工作流树吧。
Sequence sequence = new Sequence()
{
DisplayName = "My Sequence",
Activities =
{
new WriteLine()
{
Text="Start"
},
new Flowchart()
{
DisplayName = "My Flowchart",
Nodes =
{
new FlowStep()
{
Action = new If()
{
Else = new While(),
Then = new Delay()
}
}
}
},
new WriteLine()
{
Text="End"
}
}
};
看,工作流就出来了,连带着工作流的层级关系也表明了。