我想将 Dictionary 的参数传递给方法。
public static void Method(Dictionary<string, string> hash)
我真的很想使用内联集合初始化器
这是不合法的
Method({{"Foo", "Bar"}, {"Bing", "Bong"}})
这也不是
Method(new {{"Foo", "Bar"}, {"Bing", "Bong"}})
这是
// outside the class
using D = System.Collections.Generic.Dictionary<string, string>;
// calling with the type alias
Method(new D {{"Foo", "Bar"}, {"Bing", "Bong"}})
这也是
// once in a library somewhere
class SD : System.Collections.Generic.Dictionary<string, string> {}
// calling with the class
Method(new SD {{"Foo", "Bar"}, {"Bing", "Bong"}})
你有像我不知道的这样一个很好的捷径来解决我的类型集合初始化吗?
最佳答案
不,您不能按照您想要的方式声明字典。在 C#6 中,有一个稍微漂亮的 Dictionary
初始化器语法,但它并不是您想要的:
using D = System.Collections.Generic.Dictionary<string, string>;
//...
Method(new D { ["Foo"] = "Bar", ["Bing"] = "Bong" });
关于c# - 过于简洁的泛型类型的快捷方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32875785/