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

jos*_*ers 5 c# generics reflection c#-2.0

我试图在运行时派生一个对象的类型.具体来说,无论是实现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;
    }
Run Code Online (Sandbox Code Playgroud)

但我相信必须有一个比这更好的方法.我尝试过以正常方式比较,例如:

if(descriptor.PropertyType == typeof(ICollection<>))
Run Code Online (Sandbox Code Playgroud)

但是,当使用反射但未使用反射时它会失败,它可以正常工作.

我不想为我的实体的每个字段迭代接口.有人可以解释另一种方法吗?是的,我过早地进行了优化,但它看起来很难看,所以请幽默我.

注意事项:

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

提前致谢!

Pav*_*aev 11

这个:

type == typeof(ICollection)
Run Code Online (Sandbox Code Playgroud)

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

public ICollection<int> x { get; set; }
Run Code Online (Sandbox Code Playgroud)

但不适用于:

public List<int> x { get; set; }
Run Code Online (Sandbox Code Playgroud)

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

typeof(ICollection).IsAssignableFrom(type)
Run Code Online (Sandbox Code Playgroud)

通用也是如此:

typeof(ICollection<>).IsAssignableFrom(type.GetGenericTypeDefinition())
Run Code Online (Sandbox Code Playgroud)