Moh*_*had 1 .net c# keyvaluepair
我想为我的 KeyValuePair 对象分配一些静态值。
private IEnumerable<KeyValuePair<string, string>> getCountries()
{
return new List<KeyValuePair<string, string>>()
{
{ "code1", "value1" },
{ "code2", "value2" }
};
}
Run Code Online (Sandbox Code Playgroud)
但这会引发 nooverloaded 方法错误。
return new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("code1", "value1"),
new KeyValuePair<string, string>("code2", "value2"),
};
Run Code Online (Sandbox Code Playgroud)
如果您使用的是 .NET Core 2.0+,则可以使用稍微简单一点的:
return new List<KeyValuePair<string, string>>()
{
KeyValuePair.Create("code1", "value1"),
KeyValuePair.Create("code2", "value2"),
};
Run Code Online (Sandbox Code Playgroud)
在 C# 9 中,您可以使用目标类型的 new 将其写为:
return new List<KeyValuePair<string, string>>()
{
new("code1", "value1"),
new("code2", "value2"),
};
Run Code Online (Sandbox Code Playgroud)