【问题标题】:How can i pass Dictionary<string, string> to a dictionary<object,object> method?如何将 Dictionary<string, string> 传递给 dictionary<object,object> 方法?
【发布时间】:2012-05-13 03:27:44
【问题描述】:

如何将字典传递给接收字典的方法?

Dictionary<string,string> dic = new Dictionary<string,string>();

//Call
MyMethod(dic);

public void MyMethod(Dictionary<object, object> dObject){
    .........
}

【问题讨论】:

  • 这取决于上下文。你能让你的方法通用吗?你能把你的方法放在一个接口中吗?您可能有不同的解决方案。您提供的示例正是您所需要的?

标签: c# .net


【解决方案1】:

你不能按原样传递,但你可以传递一个副本:

var copy = dict.ToDictionary(p => (object)p.Key, p => (object)p.Value);

让您的 API 程序采用接口而不是类通常是个好主意,如下所示:

public void MyMethod(IDictionary<object, object> dObject) // <== Notice the "I"

这个小改动让您可以将其他类型的字典(例如 SortedList&lt;K,T&gt;)传递给您的 API。

【讨论】:

    【解决方案2】:

    如果你想以只读方式传递字典,那么你可以使用 Linq:

    MyMethod(dic.ToDictionary(x => (object)x.Key, x => (object)x.Value));
    

    由于类型安全限制,您当前的方法不起作用:

    public void MyMethod(Dictionary<object, object> dObject){
        dObject[1] = 2; // the problem is here, as the strings in your sample are expected
    }
    

    【讨论】:

      猜你喜欢
      • 2014-10-22
      • 2021-08-10
      • 2012-03-01
      • 2014-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多