我可以将集合初始化器与 NameValueCollection 一起使用吗?

有没有一种使用 C # 集合初始化器语法来初始化 NVC 的方法:

NameValueCollection nvc = new NameValueCollection() { ("a", "1"), ("b", "2") };

谢谢

21796 次浏览

Yes; just uses braces instead of parentheses.

var nvc = new NameValueCollection { {"a", "1"}, {"b", "2"} };

You can call Add methods with arbitrary sets of parameters using the syntax.

You can use collection initializers with everything that has Add method. Yeah, duck typing. If Add has more then 1 param put tuples in curly bracets:

NameValueCollection nvc = new NameValueCollection() { { "a", "1" }, { "b", "2" } };