代码之家  ›  专栏  ›  技术社区  ›  joshlrogers

使用泛型时如何比较类型?

  •  5
  • joshlrogers  · 技术社区  · 15 年前

    我正在尝试在运行时派生对象的类型。具体来说,我需要知道两件事,它是实现ICollection还是IDTO。目前我唯一能找到的解决方案是:

       private static bool IsACollection(PropertyDescriptor descriptor)
        {
            bool isCollection = false;
    
            foreach (Type type in descriptor.PropertyType.GetInterfaces())
            {
                if (type.IsGenericType)
                {
                    if (type.GetGenericTypeDefinition() == typeof(ICollection<>))
                    {
                        isCollection = true;
                        break;
                    }
                }
                else
                {
                    if (type == typeof(ICollection))
                    {
                        isCollection = true;
                        break;
                    }
                }
            }
    
    
            return isCollection;
        }
    
        private static bool IsADto(PropertyDescriptor descriptor)
        {
            bool isDto = false;
    
            foreach (Type type in descriptor.PropertyType.GetInterfaces())
            {
                if (type == typeof(IDto))
                {
                    isDto = true;
                    break;
                }
            }          
            return isDto;
        }
    

    不过,我相信一定有比这更好的方法。我试过用正常的方式进行比较,比如:

    if(descriptor.PropertyType == typeof(ICollection<>))
    

    但是,在使用反射时失败,而在不使用反射时,它可以正常工作。

    我不想遍历实体中每个字段的接口。有人能告诉你另一种方法吗?是的,我是过早优化,但它看起来也很难看,所以请幽默我。

    Caveats:

    1. 它可以是或不能是通用的,例如ilist<gt;或只是arraylist,因此我要查找iCollection或iCollection<gt;。因此,我假设应该在if语句中使用isGenericType,以了解是否使用ICollection进行测试。

    事先谢谢!

    2 回复  |  直到 15 年前
        1
  •  11
  •   Pavel Minaev    15 年前

    这是:

    type == typeof(ICollection)
    

    将检查属性类型是否为 确切地 ICollection . 也就是说,它将返回真值:

    public ICollection<int> x { get; set; }
    

    但不是为了:

    public List<int> x { get; set; }
    

    如果要检查属性类型是否为, 或来源于 , 集合 最简单的方法是 Type.IsAssignableFrom :

    typeof(ICollection).IsAssignableFrom(type)
    

    一般来说也是这样:

    typeof(ICollection<>).IsAssignableFrom(type.GetGenericTypeDefinition())
    
        2
  •  2
  •   shahkalpesh    15 年前

    type.IsAssignable 有什么帮助吗?

    编辑:对不起,应该是 Type.IsAssignableFrom