从实现IDictionary<,>的类型中获取类型参数

时间:2015-09-09 03:42:38

标签: c# generics inheritance reflection

我想编写一个函数来从实现IDictionary的类型中获取类型参数。到目前为止,我在大多数SO问题中讨论的内容是:

public static Type[] GetParameters(Type dicType) {

    if (typeof(IDictionary).IsAssignableFrom(dicType)) {
        return dicType.GetGenericArguments();
    }
    else {
        return null;
    }
}

然而,这失败了以下内容:

public class MyClass : Dictionary<string, int> { }
Type[] typeParams = GetParameters(typeof(MyClass));
Console.WriteLine(String.Join(", ", (object[]) typeParams));

它什么都不打印(空数组)。以下情况更糟糕:

public class MyOtherClass<T, U> : Dictionary<string, string> { }
Type[] typeParams = GetParameters(typeof(MyOtherClass<int, int>));
Console.WriteLine(String.Join(", ", (object[]) typeParams));

因输出完全错误(System.Int32,System.Int32)。

如何从任何继承自IDictionary的类型中获取这些参数?

1 个答案:

答案 0 :(得分:0)

在撰写问题时,我实际上想出了一个答案:

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;
}

这适用于我目前所拥有的一切。如果您有更好的想法,请发布另一个答案!

相关问题