【问题标题】:Shortcuts for overly terse generic types过于简洁的泛型类型的快捷方式
【发布时间】:2015-10-01 05:24:52
【问题描述】:

我想将 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"}})

你有像我不知道的这样一个很好的捷径来解决我的类型集合初始化吗?

【问题讨论】:

  • 我宁愿清晰而不是简洁(或者更糟糕的是,使用可以作为速记的语句),输入它有什么问题?
  • @ronBeyer 输入没问题。只是问是否完成can,而不是它should
  • stackoverflow.com/questions/1815252/… 是另一种方式,但它几乎与new Dictionary&lt;string, string&gt; { ... } 一样长。
  • 不需要匿名作为值...

标签: c# .net


【解决方案1】:

不,您不能按照您想要的方式声明字典。在 C#6 中,有一个更漂亮的 Dictionary 初始化语法,但这并不是您想要的:

using D = System.Collections.Generic.Dictionary<string, string>;

//...

Method(new D { ["Foo"] = "Bar", ["Bing"] = "Bong" });

【讨论】:

  • 对于动态二人组 Foo+Bar 的替代品感到高兴
  • @JJS 我的同事比["Shirt"] = "Pants"更可取
  • 这让我去寻找其他元语法变量名。甚至还有一个 foo RFC tools.ietf.org/html/rfc3092...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多