实现集合初始化在C#我的名单包装 [英] Implementing a collection initializer for my List wrapper in C#

查看:113
本文介绍了实现集合初始化在C#我的名单包装的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建它包装列表类:

class Wrapper
{
    private List<int> _list
}



我希望能够初始化一个新的包装对象是这样的:

I would like to be able to initialize a new Wrapper object like this:

new Wrapper() {1, 2, 3};

这是应该初始化包装的 _list 来含{1,2,3}。

That's supposed to initialize the Wrapper's _list to a list containing {1, 2, 3}.

什么我需要添加到类代码,以使该功能?

What do I need to add to the class code in order to enable the functionality?

推荐答案

您需要两样东西:


  • 您需要执行的IEnumerable (虽然其行为是不重要的集合初始本身的缘故)。您不必实施通用版本,但你的正常的希望。

  • 您需要一个添加方法接受元素类型(在这种情况下, INT )参数

  • You need to implement IEnumerable (although its behaviour is unimportant for the sake of the collection initializer itself). You don't have to implement the generic version, but you'd normally want to.
  • You need an Add method accepting the element type as a parameter (int in this case)

所以编译器会再改变这样的:

So the compiler will then transform this:

Wrapper x = new Wrapper() {1, 2, 3};



进入这样的:

Into this:

Wrapper tmp = new Wrapper();
tmp.Add(1);
tmp.Add(2);
tmp.Add(3);
Wrapper wrapper = tmp;



最简单的方法几乎肯定会委派到您的列表:

The simplest approach would almost certainly be to delegate to your list:

class Wrapper : IEnumerable<int>
{
    private readonly List<int> _list = new List<int>();

    public IEnumerator<int> GetEnumerator()
    {
        return _list.GetEnumerator();
    }

    // Explicit implementation of non-generic interface
    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    public void Add(int item)
    {
        _list.Add(item);
    }
}

如果你想使您的包装会更有效迭代,你的可能的修改的GetEnumerator 方法包括公众中返回列表< T> .Enumerator

If you want to make your wrapper slightly more efficient to iterate over, you could change the GetEnumerator methods to include a public one returning List<T>.Enumerator:

// Public method returning a mutable struct for efficiency
public List<T>.Enumerator GetEnumerator()
{
    return _list.GetEnumerator();
}

// Explicit implementation of non-generic interface
IEnumerator<int> IEnumerable<int>.GetEnumerator()
{
    return GetEnumerator();
}

// Explicit implementation of non-generic interface
IEnumerator IEnumerable.GetEnumerator()
{
    return GetEnumerator();
}

这篇关于实现集合初始化在C#我的名单包装的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆