【发布时间】: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<>))
但是,使用反射时会失败,但不使用反射时它可以正常工作。
我不想遍历我实体的每个字段的接口。有人可以阐明另一种方法吗?是的,我正在过早地优化,但它看起来也很丑,所以请幽默。
注意事项:
- 它可以是通用的,也可以不是通用的,例如 IList 或只是 ArrayList,因此我正在寻找 ICollection 或 ICollection。所以我假设我应该在 if 语句中使用 IsGenericType 来了解是否使用 ICollection 进行测试。
提前致谢!
【问题讨论】:
标签: c# generics reflection c#-2.0