我想给我的KeyValuePair对象分配一些静态值。
private IEnumerable<KeyValuePair<string, string>> getCountries()
{
return new List<KeyValuePair<string, string>>()
{
{ "code1", "value1" },
{ "code2", "value2" }
};
}但这是抛出新重载的方法错误。
发布于 2019-10-01 11:42:48
return new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("code1", "value1"),
new KeyValuePair<string, string>("code2", "value2"),
};如果您使用的是.NET Core 2.0+,则可以使用稍微少一些的2.0+:
return new List<KeyValuePair<string, string>>()
{
KeyValuePair.Create("code1", "value1"),
KeyValuePair.Create("code2", "value2"),
};在C# 9中,您可以使用目标类型的new将其写入如下:
return new List<KeyValuePair<string, string>>()
{
new("code1", "value1"),
new("code2", "value2"),
};发布于 2019-10-01 11:55:43
也可以使用Dictionary实现所需的初始化样式。
var pairs = new Dictionary<string, string>
{
{ "one", "first" },
{ "two", "second" },
}.ToList();
pairs.Should().BeOfType<List<KeyValuePair<string, string>>>(); // Pass注意,如果在后面的代码中只枚举键值对列表,则可以使用字典,而不必显式地将其转换为列表。
var pairs = new Dictionary<string, string>
{
{ "one", "first" },
{ "two", "second" },
}
// later somewhere in the code
foreach(var pair in pairs)
{
Console.WriteLine($"{pair.Key}: {pair.Value}")
}如果在内部(类内)使用值,则可以使用元组。
private IEnumerable<(string Code, string Name)> GetCountries()
{
yield return ("code", "Earth");
yield return ("code", "Vulkan");
}以后可以以更易读的方式使用。
foreach(var country in GetCountries())
{
Console.WriteLine($"{country.Code}: {country.Name}")
}如果跨应用程序使用类型,那么您可以向代码的读者展示代码的意图并创建自定义类型,而不是使用键值对。
public class Country
{
public string Code { get; }
public string Name { get; }
public Country(string code, string name)
{
Code = code;
Name = name;
}
}
private IEnumerable<Country> GetCountries()
{
yield return new Country("code", "Earth");
yield return new Country("code", "Vulkan");
}以后可以以更易读的方式使用。
foreach(var country in GetCountries())
{
Console.WriteLine($"{country.Code}: {country.Name}")
}发布于 2019-10-01 11:55:19
您需要考虑泛型类的键属性和值属性都是只读属性,因此不能直接设置它们。相反,您需要利用类的构造函数来设置所需的对。
public IEnumerable<KeyValuePair<string, string>> getCountries()
{
var keyValue1 = new KeyValuePair<string,string>("code1","value1");
var keyvalue2 = new KeyValuePair<string,string>("code2","value2");
var keyValueList = new List<KeyValuePair<string, string>> {keyValue1, keyvalue2};
return keyValueList;
}https://stackoverflow.com/questions/58184056
复制相似问题