代码之家  ›  专栏  ›  技术社区  ›  Nick

将泛型词典转换为不同类型

  •  13
  • Nick  · 技术社区  · 16 年前

    有没有一种快速的方法可以将泛型词典从一种类型转换为另一种类型

    我有这个

    IDictionary<string, string> _commands;
    

    public void Handle(IDictionary<string, Object> _commands);
    
    4 回复  |  直到 16 年前
        1
  •  22
  •   mqp    16 年前

    我想我会写

    Handle(_commands.ToDictionary(p => p.Key, p => (object)p.Value));
    

    这不是世界上最有效的方法,但在协方差出现之前,这就是突破。

        2
  •  1
  •   Jhonny D. Cano -Leftware-    16 年前

    也许这个功能对你有用

    IEnumerable<KeyValuePair<string, object>> Convert(IDictionary<string, string> dic) {
        foreach(var item in dic) {
            yield return new KeyValuePair<string, object>(item.Key, item.Value);
        }
    }
    

    你会这样称呼它:

    Handle(Convert(_commands));
    
        3
  •  0
  •   Franzitaly    14 年前

    Dictionary<int, string> dict = new Dictionary<int, string>();
    
    dict.Add(1, "One");
    dict.Add(2, "Two");
    dict.Add(3, "Three");
    dict.Add(4, "Four");
    dict.Add(5, "Five");
    
    object dictObj = (object)dict;
    
    IDictionary temp = (IDictionary)dictObj;
    
    Dictionary<int, object> objs = new Dictionary<int, object>();
    
    foreach (DictionaryEntry de in temp)
    {
        objs.Add((int)de.Key, (object)de.Value);
    }
    
        4
  •  0
  •   DaveShaw Thishin    13 年前

    你不能用吗

    Dim myDictionary AS New Dictionary(Of Object, Object)
    

    然后,它将能够接受任何类型