Simplified Collection initialization

前端 未结 1 1592
死守一世寂寞
死守一世寂寞 2021-01-14 19:52

While initializing WF4 activities we can do something like this:

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


        
相关标签:
1条回答
  • 2021-01-14 20:04

    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();
        }  
    }
    
    0 讨论(0)
提交回复
热议问题