如何将字典传递给接收字典的方法?
Dictionary<string,string> dic = new Dictionary<string,string>();
//Call
MyMethod(dic);
public void MyMethod(Dictionary<object, object> dObject){
.........
}
你不能按原样传递它,但你可以传递一个副本:
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。
如果您想将字典传递给只读目的,那么您可以使用 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
}