相关疑难解决方法(0)

通用集合类型测试

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

这是我的代码:

    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)

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

c# types generic-collections

5
推荐指数
1
解决办法
802
查看次数

标签 统计

c# ×1

generic-collections ×1

types ×1