或者使用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}")
}