Simplified Collection initialization

拜拜、爱过 提交于 2019-12-30 10:47:06

问题


While initializing WF4 activities we can do something like this:

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

Note that Sequence.Activities is a Collection<Activity> but it can be initialized without the new Collection().

How can I emulate this behaviour on my Collection<T> properties?


回答1:


Any collection that has an Add() method and implements IEnumerable can be initialized this way. For details, refer to Object and Collection Initializers for C#. (The lack of the new Collection<T> call is due to an object initializer, and the ability to add the items inline is due to the collection initializer.)

The compiler will automatically call the Add() method on your class with the items within the collection initialization block.


As an example, here is a very simple piece of code to demonstrate:

using System;
using System.Collections.ObjectModel;

class Test
{
    public Test()
    {
        this.Collection = new Collection<int>();
    }

    public Collection<int> 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();
    }  
}


来源:https://stackoverflow.com/questions/5793286/simplified-collection-initialization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!