I would like to write a function to get the type parameters from types implementing IDictionary. What I have so far, and what is discussed in most SO questions is:
public static Type[] GetParameters(Type dicType) {
if (typeof(IDictionary).IsAssignableFrom(dicType)) {
return dicType.GetGenericArguments();
}
else {
return null;
}
}
However this fails with the following:
public class MyClass : Dictionary<string, int> { }
Type[] typeParams = GetParameters(typeof(MyClass));
Console.WriteLine(String.Join(", ", (object[]) typeParams));
which would print nothing (empty array). This is even worse with the following:
public class MyOtherClass<T, U> : Dictionary<string, string> { }
Type[] typeParams = GetParameters(typeof(MyOtherClass<int, int>));
Console.WriteLine(String.Join(", ", (object[]) typeParams));
as the output is completely wrong (System.Int32, System.Int32).
How can I get these parameters for any type that inherits from IDictionary ?
Aucun commentaire:
Enregistrer un commentaire