使用数组语法初始化我的类

时间:2014-11-07 13:03:01

标签: c# .net class oop constructor

无论如何都要像数组或字典一样初始化我的类,例如

    private class A
    {
        private List<int> _evenList;
        private List<int> _oddList;
        ...
    }

并说

A a = new A {1, 4, 67, 2, 4, 7, 56};

在我的构造函数中填充_ evenList 和_ oddList 及其值。

2 个答案:

答案 0 :(得分:6)

要使用collection initializer,您的班级必须:

  • 实施IEnumerable
  • 实施适当的Add方法

例如:

class A : IEnumerable
{
    private List<int> _evenList = new List<int>();
    private List<int> _oddList = new List<int>();

    public void Add(int value)
    {
        List<int> list = (value & 1) == 0 ? _evenList : _oddList;
        list.Add(value);
    }

    // Explicit interface implementation to discourage calling it.
    // Alternatively, actually implement it (and IEnumerable<int>)
    // in some fashion.
    IEnumerator IEnumerable.GetEnumerator()
    {
        throw new NotImplementedException("Not really enumerable...");
    }
}

答案 1 :(得分:0)

我能想到的唯一方法是将数组传递给构造函数

private class A
{
    private List<int> _evenList;
    private List<int> _oddList;

    public A (int[] input)
    {
        ... put code here to load lists ...
    }
}

用法:

A foo = new A({1, 4, 67, 2, 4, 7, 56});