c# - 过于简洁的泛型类型的快捷方式

标签 c# .net

我想将 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/

相关文章:

c# - 有没有一种方法可以像使用 C# 的 MS Office Excel 一样创建/读取 LibreOffice 电子表格?

c# - 如何根据条件更改 ListView 中的 Textcoroul 或 TextCell 的背景颜色

c# - .NET对象事件和处置/GC

.net - 当 Key 和 Value 相同时使用字典?

.net - 如何从 .NET 中的 CultureInfo 获取 ISO 3166 国家/地区代码

c# - XInclude 的替代品

c# - 在 C# 中从当前窗体调用新窗体

c# - 为查询数据库的方法编写单元测试

c# - 如何将对象转换为泛型?

.net - 我们什么时候需要注册 .Net dll 和 COM dll?