c# - 使用泛型时如何比较类型?

标签 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;
    }

但是我相信一定有比这更好的方法。我尝试以正常方式进行比较,例如:

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

然而,当使用反射时,这会失败,但当不使用反射时,它工作正常。

我不想遍历我实体的每个字段的接口(interface)。有人可以阐明执行此操作的另一种方法吗?是的,我过早地优化了,但它看起来也很丑,所以请幽默一下。

注意事项:

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

提前致谢!

最佳答案

这个:

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())

关于c# - 使用泛型时如何比较类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1201753/

相关文章:

ios - 如果让 OR 条件

.net - 获取不带 "Attribute"的属性类型名称

c# - 在 Release模式下没有获取当前工作目录?

c# - 如何防止在本地缓存 PDF?

c# - MVC 5 经过身份验证的用户正在注销,没有 "remember me"(ExpireTimeSpan/MachineKey/Session Timeout)

c# - 动态代码生成

Java - 使用反射获取对静态类的引用

C# 从循环中启动线程抛出 IndexOutOfBoundsException

c# - 非泛型类中泛型类型的属性

generics - 如何在 F# 中正确使用 .NET 7 中的 INumber?