C# 如何将对象初始值设定项用于键值对列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11694910/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you use object initializers for a list of key value pairs?
提问by loyalflow
I can't figure out the syntax to do inline collection initialization for:
我无法弄清楚进行内联集合初始化的语法:
var a = new List<KeyValuePair<string, string>>();
采纳答案by digEmAll
Pretty straightforward:
非常简单:
var a = new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("A","B"),
new KeyValuePair<string, string>("A","B"),
new KeyValuePair<string, string>("A","B"),
};
Note that you can leave the trailing comma after the last element (probably because .net creators wanted to make automatic code-generation easier), or remove the ()brackets of the list contructor and the code still compiles.
请注意,您可以在最后一个元素之后留下尾随逗号(可能是因为 .net 创建者希望使自动代码生成更容易),或者删除()列表构造函数的括号,代码仍然可以编译。
回答by burning_LEGION
Any initialization is done by object(params_if_exist) { any public member or instance};
任何初始化都由 object(params_if_exist) { any public member or instance};
f.e. var list = new List<int> {1,2,3};
铁 var list = new List<int> {1,2,3};
var bw = new BackgroundWorker() {WorkerSupportsCancellation = true};
var bw = new BackgroundWorker() {WorkerSupportsCancellation = true};
回答by phoog
Note that the dictionary collection initialization { { key1, value1 }, { key2, value2 } }depends on the Dictionary's Add(TKey, TValue)method. You can't use this syntax with the list because it lacks that method, but you could make a subclass with the method:
请注意,字典集合的初始化{ { key1, value1 }, { key2, value2 } }取决于字典的Add(TKey, TValue)方法。您不能将此语法用于列表,因为它缺少该方法,但您可以使用该方法创建一个子类:
public class KeyValueList<TKey, TValue> : List<KeyValuePair<TKey, TValue>>
{
public void Add(TKey key, TValue value)
{
Add(new KeyValuePair<TKey, TValue>(key, value));
}
}
public class Program
{
public static void Main()
{
var list = new KeyValueList<string, string>
{
{ "key1", "value1" },
{ "key2", "value2" },
{ "key3", "value3" },
};
}
}
回答by elRobbo
Another alternative that doesn't require making a subclass:
另一种不需要创建子类的替代方法:
List<KeyValuePair<String, String>> list = new Dictionary<String, String>
{
{"key1", "value1"},
{"key2", "value2"},
}.ToList();
As mentioned in the comments: drawbacks with this method include possible loss of ordering and inability to add duplicate keys.
如评论中所述:此方法的缺点包括可能会丢失排序和无法添加重复键。
回答by user764754
Since collection initializers (C# 6.0) have not been mentioned here:
由于这里没有提到集合初始值设定项(C# 6.0):
Implementation
执行
public static class InitializerExtensions
{
public static void Add<T1, T2>(this ICollection<KeyValuePair<T1, T2>> target, T1 item1, T2 item2)
{
if (target == null)
throw new ArgumentNullException(nameof(target));
target.Add(new KeyValuePair<T1, T2>(item1, item2));
}
}
Usage
用法
var list = new List<KeyValuePair<string, string>> { {"ele1item1", "ele1item2"}, { "ele2item1", "ele2item2" } };
How to make it work
如何让它发挥作用
Just include the right usingstatements in your file so that InitializerExtensionsis available (meaning you could call InitializerExtensions.Addexplicitly) and the special collection initializer syntax will become available if you are using VS 2015 or higher.
只需using在您的文件中包含正确的语句,以便InitializerExtensions可用(意味着您可以InitializerExtensions.Add显式调用),如果您使用 VS 2015 或更高版本,则特殊的集合初始值设定项语法将可用。

