Generic collections type test

强颜欢笑 提交于 2019-12-10 14:27:23

问题


I'd like to make some operations according to a given collection type (using reflexion), regardless of the generic type.

Here is my code:

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

It works for now, but it gets obvious to me that it's not the most safe solution.

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

I tried that too, it actualy compiles but doesn't work... I also tried to test all interfaces of the given collection type, but it implies an exclusivity for interfaces in collections...

I hope I made myself clear, my english lack of training :)


回答1:


If you want to see if something implements a specific generic type, then you would need to do this:

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

The GetGenericTypeDefinition() method will return the unbounded generic type for you test against.



来源:https://stackoverflow.com/questions/10355635/generic-collections-type-test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!