【问题标题】:Initialize my class with array syntax用数组语法初始化我的类
【发布时间】:2015-01-04 06:44:39
【问题描述】:

是否可以像数组或字典一样初始化我的类,例如

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

然后说

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

并在我的构造函数中填充 _evenList 和 _oddList 的值。

【问题讨论】:

  • 为evenList选择偶数值,为oddList选择奇数值

标签: c# .net class oop constructor


【解决方案1】:

要使用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...");
    }
}

【讨论】:

  • 你确定我可以用这个吗:new A {1, 4, 67, 2, 4, 7, 56};与那个
  • @AlexanderLeyvaCaro:你确定不能吗? (提示:试试看。)
  • 如果我使用字典语法,它是怎样的?
  • @AlexanderLeyvaCaro:“字典语法”是什么意思?
  • 像这样:新 A {{1,3,5},{2,4,6}}
【解决方案2】:

我能想到的唯一方法是通过构造函数传递你的数组

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

【讨论】:

  • @JonSkeet,的确,如果一个人保持开放的心态,每天都会学到一些新东西。我撤回了我的回答,因为 Jon 的表现要好得多。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-01
  • 2011-08-06
  • 2016-09-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多