我正在尝试在运行时派生对象的类型。具体来说,我需要知道两件事是它实现了 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)。有人可以阐明执行此操作的另一种方法吗?是的,我过早地优化了,但它看起来也很丑,所以请幽默一下。
注意事项:
- 它可以是也可以不是通用的,例如 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/