通用集合类型测试

时间:2012-04-27 18:02:49

标签: c# types generic-collections

我想根据给定的集合类型(使用反射)进行一些操作,而不管泛型类型。

这是我的代码:

    void MyFct(Type a_type)
    {
        // Check if it's type of List<>
        if (a_type.Name == "List`1")
        {
            // Do stuff
        }
        // Check if it's type of Dictionary<,>
        else if (a_type.Name == "Dictionary`2")
        {
            // Do stuff
        }
    }

它现在有效,但对我来说很明显,这不是最安全的解决方案。

    void MyFct(Type a_type)
    {
        // Check if it's type of List<>
        if (a_type == typeof(List<>))
        {
            // Do stuff
        }
        // Check if it's type of Dictionary<,>
        else if (a_type == typeof(Dictionary<,>))
        {
            // Do stuff
        }
    }

我也尝试过,它实际编译但不起作用...... 我还尝试测试给定集合类型的所有接口,但它意味着集合中接口的排他性......

我希望自己明确表示,我的英语缺乏训练:)

1 个答案:

答案 0 :(得分:8)

如果您想查看某些东西是否实现了特定的泛型类型,那么您需要这样做:

if(a_type.IsGenericType && a_type.GetGenericTypeDefinition() == typeof(List<>))

GetGenericTypeDefinition()方法将返回针对您进行测试的无界泛型类型。