我有一个场景,我有一个自定义映射类.
我希望能够同时创建新实例并为其声明数据,并实现类似于以下的语法:
public static HybridDictionary Names = new HybridDictionary()
{
{People.Dave, "Dave H."},
{People.Wendy, "Wendy R."}
}
Run Code Online (Sandbox Code Playgroud)
等等.如何定义我的类来启用这种语法?
你想要实现的是一个收集初始化器
你的HybridDictionary类需要实现IEnumerable <>并有一个像这样的Add方法:
public void Add(People p, string name)
{
....
}
Run Code Online (Sandbox Code Playgroud)
然后你的实例应该有效.
注意:按照惯例,键应该是第一个参数后跟值(即void Add(字符串键,People值).
基本上,您应该实现 ICollection<T> ,但这里有更详细的解释:http://blogs.msdn.com/madst/archive/2006/10/10/What-is-a-collection_3F00_.aspx。
Mads Torgersen 在文章中解释了使用基于模式的方法,因此唯一的要求是您需要有一个具有正确参数的公共 Add 方法并实现 IEnumerable。换句话说,这段代码是有效的并且可以工作:
using System.Collections;
using System.Collections.Generic;
class Test
{
static void Main()
{
var dictionary = new HybridDictionary<string, string>
{
{"key", "value"},
{"key2", "value2"}
};
}
}
public class HybridDictionary<TKey, TValue> : IEnumerable<KeyValuePair<TKey, TValue>>
{
private readonly Dictionary<TKey, TValue> inner = new Dictionary<TKey, TValue>();
public void Add(TKey key, TValue value)
{
inner.Add(key, value);
}
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
return inner.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
Run Code Online (Sandbox Code Playgroud)