2012-10-29 19 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"); 
相关问题