我无法弄清楚内联集合初始化的语法:
var a = new List<KeyValuePair<string, string>>();
Run Code Online (Sandbox Code Playgroud)
pho*_*oog 74
请注意,字典集合初始化{ { key1, value1 }, { key2, value2 } }
取决于Dictionary的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" },
};
}
}
Run Code Online (Sandbox Code Playgroud)
dig*_*All 71
很简单:
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"),
};
Run Code Online (Sandbox Code Playgroud)
请注意,您可以在最后一个元素之后留下尾随逗号(可能是因为.net创建者想要使自动代码生成更容易),或者删除()
列表构造函数的括号并且代码仍然编译.
elR*_*bbo 10
另一个不需要创建子类的替代方法:
List<KeyValuePair<String, String>> list = new Dictionary<String, String>
{
{"key1", "value1"},
{"key2", "value2"},
}.ToList();
Run Code Online (Sandbox Code Playgroud)
正如评论中所提到的:此方法的缺点包括可能丢失排序和无法添加重复键.
由于这里没有提到集合初始化器(C#6.0):
实作
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));
}
}
Run Code Online (Sandbox Code Playgroud)
用法
var list = new List<KeyValuePair<string, string>> { {"ele1item1", "ele1item2"}, { "ele2item1", "ele2item2" } };
Run Code Online (Sandbox Code Playgroud)
如何运作
只需using
在文件中包括正确的语句即可InitializerExtensions
使用(这意味着您可以InitializerExtensions.Add
显式调用),并且如果使用VS 2015或更高版本,则特殊的集合初始化语法将变得可用。
归档时间: |
|
查看次数: |
36006 次 |
最近记录: |