jeudi 28 janvier 2016

Determine if a type is convertible to IDictionary

Let's say we have a type that implements IDictionary<string, string>. It's called MyStringDictionary.

I'm doing some property/field/method reflection and would like to know if the member is a type that I can convert to an IDictionary<string, object>.

I know that typeof(IDictionary<string, string>).IsAssignableFrom(typeof(MyStringDictionary)) will be true since both generic parameters match. However, I won't be doing direct assignment to <string, string> but instead will be converting to <string, object>, something like this:

public class MyStringDictionary : IDictionary<string, string> {
   // Notice that the class itself has no generic type arguments!
}

MyStringDictionary myStringDictionary = GetBigDictionary();
IDictionary<string, object> = myStringDictionary
   .ToDictionary(kvp => kvp.Key, kvp => (object) kvp.Value);

How can I determine that this conversion is possible?

I was thinking that I can look to see if it implements IEnumerable<KeyValuePair<,>>, but again I'm stymied by the fact that I don't know the type argument of the Value, and don't need to know it because it will just be boxed to object.





Aucun commentaire:

Enregistrer un commentaire