【问题标题】:How do I compare types when using generics?使用泛型时如何比较类型?
【发布时间】:2009-07-29 17:11:19
【问题描述】:

我试图在运行时派生对象的类型。具体来说,我需要知道两件事是实现 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<>))

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

我不想遍历我实体的每个字段的接口。有人可以阐明另一种方法吗?是的,我正在过早地优化,但它看起来也很丑,所以请幽默。

注意事项:

  1. 它可以是通用的,也可以不是通用的,例如 IList 或只是 ArrayList,因此我正在寻找 ICollection 或 ICollection。所以我假设我应该在 if 语句中使用 IsGenericType 来了解是否使用 ICollection 进行测试。

提前致谢!

【问题讨论】:

    标签: c# generics reflection c#-2.0


    【解决方案1】:

    这个:

    type == typeof(ICollection)
    

    将检查属性类型是否准确 ICollection。也就是说,它将返回 true:

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

    但不适用于:

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

    如果要检查属性的类型是,还是派生自ICollection,最简单的方法是使用Type.IsAssignableFrom

    typeof(ICollection).IsAssignableFrom(type)
    

    通用也是如此:

    typeof(ICollection<>).IsAssignableFrom(type.GetGenericTypeDefinition())
    

    【讨论】:

    • 实际上他正在遍历整个层次结构。此外,ICollection 不直接实现 ICollection。
    • 这样做了,我把这些命令的顺序颠倒了!我在做 typeof(IList).IsAssignableFrom(typeof(ICollection)。非常感谢!
    • 这对我不起作用。我不得不发帖another question
    【解决方案2】:

    type.IsAssignable 在这种情况下有帮助吗?

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

    【讨论】:

    • 很遗憾没有。当我检查 property.PropertyType.IsAssignableFrom(ICollection) 并且类型是 IList 它仍然失败。不过谢谢。
    猜你喜欢
    • 2010-12-29
    • 2020-09-28
    • 1970-01-01
    • 1970-01-01
    • 2011-04-27
    • 1970-01-01
    相关资源
    最近更新 更多