简化的集合初始化

在初始化WF4活动时,我们可以这样做:

Sequence s = new Sequence() { Activities = { new If() ..., new WriteLine() ..., } } 

请注意, Sequence.ActivitiesCollection但可以在没有新Collection()的情况下初始化它。

如何在Collection属性上模拟此行为?

任何具有Add()方法并实现IEnumerable集合都可以通过这种方式初始化。 有关详细信息,请参阅C#的对象和集合初始化程序 。 (缺少新的Collection调用是由于对象初始化程序,并且内联项添加的能力是由于集合初始化程序。)

编译器将使用集合初始化块中的项自动调用类的Add()方法。


举个例子,这是一段非常简单的代码来演示:

 using System; using System.Collections.ObjectModel; class Test { public Test() { this.Collection = new Collection(); } public Collection Collection { get; private set; } public static void Main() { // Note the use of collection intializers here... Test test = new Test { Collection = { 3, 4, 5 } }; foreach (var i in test.Collection) { Console.WriteLine(i); } Console.WriteLine("Press any key to exit..."); Console.ReadKey(); } }