通用集合类型测试

s0u*_*bap 5 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
        }
    }
Run Code Online (Sandbox Code Playgroud)

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

    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
        }
    }
Run Code Online (Sandbox Code Playgroud)

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

我希望我说清楚,我的英语缺乏训练:)

Tej*_*ejs 9

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

if(a_type.IsGenericType && a_type.GetGenericTypeDefinition() == typeof(List<>))
Run Code Online (Sandbox Code Playgroud)

GetGenericTypeDefinition()方法将返回无限制的泛型类型供您测试.