【问题标题】:Assigning Values to KeyValuePair为 KeyValuePair 赋值
【发布时间】:2019-10-01 11:39:03
【问题描述】:

我想为我的 KeyValuePair 对象分配一些静态值。

private IEnumerable<KeyValuePair<string, string>> getCountries()
{
    return new List<KeyValuePair<string, string>>() 
    { 
      { "code1", "value1" }, 
      { "code2", "value2" } 
    };
}

但这会引发 nooverloaded 方法错误。

【问题讨论】:

标签: c# .net keyvaluepair


【解决方案1】:
return new List<KeyValuePair<string, string>>()
{
    new KeyValuePair<string, string>("code1", "value1"),
    new KeyValuePair<string, string>("code2", "value2"),
};

如果您使用的是 .NET Core 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"),
};

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 请注意,不能保证您以正确的顺序获取元素。使用 Dictionary 的当前实现,您会这样做,但不保证将来会如此。
    • @canton7,当前的 Dictionary 实现能保证吗?
    • 没有任何保证。碰巧当前的 Dictionary 实现将按插入顺序返回项目除非您删除/替换项目,但这在任何时候都不能保证。
    • @canton7,但是 List 有这样的保证,即使您删除/添加/替换项目,值也会以相同的顺序返回?
    • 是的,一个 List 有一个指定的顺序。字典没有。
    【解决方案3】:

    需要考虑泛型类的 Key 和 Value 属性都是只读的,所以不能直接设置。相反,您需要利用类的构造函数来设置所需的对。

    
    
     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;
    
       }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 2014-05-12
      • 1970-01-01
      • 1970-01-01
      • 2012-11-07
      • 1970-01-01
      相关资源
      最近更新 更多