![](/img/trans.png)
[英]how can i include my array property into class constructor and be able to access it via object initialization?
[英]How can I implement a constructor with inline initialization for a custom map class?
我有一個場景,我有一個自定義映射類。
我希望能夠同時創建新實例並為其聲明數據,並實現類似於以下的語法:
public static HybridDictionary Names = new HybridDictionary()
{
{People.Dave, "Dave H."},
{People.Wendy, "Wendy R."}
}
等等。 如何定義我的類來啟用這種語法?
你想要實現的是一個收集初始化器
你的HybridDictionary類需要實現IEnumerable <>並有一個像這樣的Add方法:
public void Add(People p, string name)
{
....
}
然后你的實例應該有效。
注意:按照慣例,鍵應該是第一個參數后跟值(即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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.