如何将Dictionary <string,string =“”>传递给字典<object,object>方法?</object,object> </string,>

时间:2012-05-03 15:18:27

标签: c# .net

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

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

//Call
MyMethod(dic);

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

2 个答案:

答案 0 :(得分:8)

您无法按原样传递,但您可以传递副本:

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

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

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

这一小改动可让您将其他类型的词典(例如SortedList<K,T>)传递给您的API。

答案 1 :(得分:1)

如果您想以只读方式传递字典,那么您可以使用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
}