2012-10-29 15 views
0

我需要傳遞html屬性。如何將實體添加到Dictionary對象初始值設定項?

有可能打包成一個這樣的表達代碼?

var tempDictionary = new Dictionary<string, object> { 
    { "class", "ui-btn-test" }, 
    { "data-icon", "gear" } 
}.Add("class", "selected"); 

new Dictionary<string, object>().Add("class", "selected").Add("diabled", "diabled"); 

+0

這是沒有意義的,使用集合初始值設定項或Add() – sll

回答

1

你指的是被稱爲方法鏈。一個很好的例子就是StringBuilder的Append方法。

StringBuilder b = new StringBuilder(); 
b.Append("test").Append("test"); 

這是可能的,因爲追加方法返回一個StringBuilder對象

public unsafe StringBuilder Append(string value) 

但是,在你的情況下,Dictionary<TKey, TValue> Add方法被標記爲無效

public void Add(TKey key, TValue value) 

因此,方法鏈接不受支持。但是,如果你真的想要增加新的項目時,使用方法鏈,你總是可以滾你自己:

public static Dictionary<TKey, TValue> AddChain<TKey, TValue>(this Dictionary<TKey, TValue> d, TKey key, TValue value) 
{ 
    d.Add(key, value); 
    return d; 
} 

然後,你可以寫代碼如下:

Dictionary<string, string> dict = new Dictionary<string, string>() 
    .AddChain("test1", "test1") 
    .AddChain("test2", "test2"); 
相關問題