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

Rap*_*ael 4 .net c#

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

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

//Call
MyMethod(dic);

public void MyMethod(Dictionary<object, object> dObject){
    .........
}
Run Code Online (Sandbox Code Playgroud)

das*_*ght 8

您不能按原样传递,但您可以传递副本:

var copy = dict.ToDictionary(p => (object)p.Key, p => (object)p.Value);
Run Code Online (Sandbox Code Playgroud)

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

public void MyMethod(IDictionary<object, object> dObject) // <== Notice the "I"
Run Code Online (Sandbox Code Playgroud)

这个小小的改动让你可以传递其他类型的词典,例如SortedList<K,T>你的API.