簡單:
ListBoxes.Add(
new KeyValuePair<string, List<KeyValuePair<string, List<KeyValuePair<string, bool>>>>>("A",
new List<KeyValuePair<string, List<KeyValuePair<string, bool>>>>
{
new KeyValuePair<string,List<KeyValuePair<string,bool>>>("B",
new List<KeyValuePair<string,bool>>() {
new KeyValuePair<string,bool>("C", true)
}
)
}
)
);
看起來你可以使用一些輔助方法什麼的。
編輯
如果您創建一個簡單的擴展方法,那麼任務就變得可能可讀性更強一些。
public static List<KeyValuePair<TKey, TValue>> AddKVP<TKey, TValue>(this List<KeyValuePair<TKey, TValue>> self, TKey key, TValue value)
{
self.Add(
new KeyValuePair<TKey, TValue>(key, value)
);
// return self for "fluent" like syntax
return self;
}
var c = new List<KeyValuePair<string, bool>>().AddKVP("c", true);
var b = new List<KeyValuePair<string, List<KeyValuePair<string, bool>>>>().AddKVP("b", c);
var a = new List<KeyValuePair<string, List<KeyValuePair<string, List<KeyValuePair<string, bool>>>>>>().AddKVP("a", b);
編輯#2
如果定義了一個簡單的類型,那麼它可以幫助多一點:
public class KVPList<T> : List<KeyValuePair<string, T>> { }
public static KVPList<TValue> AddKVP<TValue>(this KVPList<TValue> self, string key, TValue value)
{
self.Add(new KeyValuePair<string, TValue>(key, value));
return self;
}
var ListBoxes = new KVPList<KVPList<KVPList<bool>>>()
.AddKVP("A", new KVPList<KVPList<bool>>()
.AddKVP("B", new KVPList<bool>()
.AddKVP("C", true)));
編輯#3
還有一個和我承諾我會停止。如果你定義的類型「添加」,然後就可以使用隱式初始化:
public class KVPList<T> : List<KeyValuePair<string, T>>
{
public void Add(string key, T value)
{
base.Add(new KeyValuePair<string,T>(key, value));
}
}
var abc = new KVPList<KVPList<KVPList<bool>>> {
{ "A", new KVPList<KVPList<bool>> {
{ "B", new KVPList<bool> {
{ "C", true }}
}}
}};
,而不是去如此之深成泛型兔子洞,你爲什麼不寫一個自定義的類,它_exactly_你需要什麼? – Oded
或者幾個,考慮到嵌套水平,你似乎需要多個類。 – Servy
原因使用這麼多classess似乎他們需要更多內存列表的列表:) –