简体   繁体   中英

How to cast a generic type when parameters differ but are convertable?

I have a method parameter that takes IDictionary<string,string> but I would like to pass it an IDictionary<string,JToken> (Newtonsoft.Json).

The cast fails at runtime but since JToken provides both implicit and explicit conversion methods, I thought there might be a way to cast.

How can this cast be achieved?

class MyClass
{
    void Method(IDictionary<string,string> data) {}
}

...
IDictionary<string,JToken> record = ...;
MyClass cls = new MyClass();
cls.Method((IDictionary<string,string>)record);
...

You cant Cast from one to the other, pretty much the only way is to create a new Dictionary:

IDictionary<string,JToken> record = ...;
MyClass cls = new MyClass();
cls.Method(record.ToDictionary(k => k.Key,v => (string)v.Value));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM