c# - 在自定义类上创建字典样式的集合初始值设定项

标签 c# dictionary

<分区>

Possible Duplicate:
Custom Collection Initializers

我有一个简单的 Pair 类:

public class Pair<T1, T2>
    {
        public Pair(T1 value1, T2 value2)
        {
            Value1 = value1;
            Value2 = value2;
        }

        public T1 Value1 { get; set; }
        public T2 Value2 { get; set; }
    }

并且希望能够像 Dictionary 对象一样定义它,像这样内联:

var temp = new Pair<int, string>[]
        {
            {0, "bob"},
            {1, "phil"},
            {0, "nick"}
        };

但它要求我定义一个全新的 Pair(0, "bob") 等,我将如何实现它?

像往常一样,谢谢大家!

最佳答案

要使自定义初始化像字典一样工作,您需要支持两件事。您的类型需要实现 IEnumerable 并具有适当的 Add 方法。您正在初始化一个 Array,它没有 Add 方法。例如

class PairList<T1, T2> : IEnumerable
{
    private List<Pair<T1, T2>> _list = new List<Pair<T1, T2>>();

    public void Add(T1 arg1, T2 arg2)
    {
        _list.Add(new Pair<T1, T2>(arg1, arg2));
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return _list.GetEnumerator();
    }
}

然后你可以做

var temp = new PairList<int, string>
{
    {0, "bob"},
    {1, "phil"},
    {0, "nick"}
};

关于c# - 在自定义类上创建字典样式的集合初始值设定项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9570245/

相关文章:

Java HashMap 具有重复键的疯狂行为

java - 如何用最少的资源循环 map ?

python: 打印 __dict__ :是否可以按照类中列出的顺序打印?

c# - .NET 中的 WMI 访问是否需要管理权限?

c# - 测试 lambda 表达式相等性的最有效方法

c# - c#中两位小数的数字分组

arrays - 我想从多个 tableView 选择创建一个数组

ios - 一键Swift对应多个字典的字典

c# - BackgroundWorker 返回一个值?

c# - Windows 8 中的 Windows Azure 和 Metro 风格的应用程序