[英]Get type parameters from type implementing IDictionary<,>
I would like to write a function to get the type parameters from types implementing IDictionary. 我想编写一个函数来从实现IDictionary的类型中获取类型参数。 What I have so far, and what is discussed in most SO questions is:
到目前为止,在大多数SO问题中讨论的是:
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). 因为输出完全错误(System.Int32,System.Int32)。
How can I get these parameters for any type that inherits from IDictionary ? 我如何获取从IDictionary继承的任何类型的这些参数?
While writing the question, I actually came up with an answer: 在写问题时,我实际上想出了一个答案:
public static Type[] GetDictionaryParameters(Type dicType) {
foreach(var interf in dicType.GetInterfaces()) {
if (interf.IsGenericType && interf.GetGenericTypeDefinition() == typeof(IDictionary<,>)) {
return interf.GetGenericArguments();
}
}
// No matching interface
return null;
}
This works with everything I have so far. 这适用于我到目前为止的所有内容。 If you have a better idea, please post another answer !
如果您有更好的主意,请发布另一个答案!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.