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

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

  •  12
  • Nick  · 技术社区  · 15 年前

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

    我有这个

    IDictionary<string, string> _commands;
    

    并且需要将其传递给一个函数,该函数采用一个稍微不同的类型字典

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

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

    这不是世界上最有效率的事情,但在协方差出现之前,这就是休息。

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

    也许这个函数对你有用

    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    13 年前

    这样可以吗?

    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    12 年前

    你不能用吗

    Dim myDictionary AS New Dictionary(Of Object, Object)
    

    这样就可以接受任何类型