本文介绍了简化集合初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

While initializing WF4 activities we can do something like this:

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

注意 Sequence.Activities Collection< Activity>

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

如何在我的 code>集合< T> 属性?

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

推荐答案

c $ c> Add()方法并实现 IEnumerable 可以这种方式初始化。有关详细信息,请参阅。 (缺少新的集合< T> 调用是由于对象初始化器,并且能够在内联中添加项目是由于集合初始化器。)

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.)

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

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

这篇关于简化集合初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 20:20