我如何知道某个属性是否是通用集合
我需要使用 PropertyInfo 类了解类中属性的类型是否是通用集合(List、ObservableCollection)。
foreach (PropertyInfo p in (o.GetType()).GetProperties())
{
if(p is Collection<T> ????? )
}
I need to know if the type of a property in a class is a generic collection (List, ObservableCollection) using the PropertyInfo class.
foreach (PropertyInfo p in (o.GetType()).GetProperties())
{
if(p is Collection<T> ????? )
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要测试
t.IsGenericType
和x.IsGenericType
,否则如果类型不是泛型,GetGenericTypeDefinition()
将引发异常。如果属性声明为
ICollection
,则tColl.IsAssignableFrom(t.GetGenericTypeDefinition())
将返回true
。如果该属性被声明为实现
ICollection
的类型,则t.GetInterfaces().Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == tColl)
将返回true
。请注意,例如,对于
List
,tColl.IsAssignableFrom(t.GetGenericTypeDefinition())
返回false
。我已经测试了所有这些组合的
MyT o = new MyT();
输出:
You need the tests
t.IsGenericType
andx.IsGenericType
, otherwiseGetGenericTypeDefinition()
will throw an exception if the type is not generic.If the property is declared as
ICollection<T>
thentColl.IsAssignableFrom(t.GetGenericTypeDefinition())
will returntrue
.If the property is declared as a type which implements
ICollection<T>
thent.GetInterfaces().Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == tColl)
will returntrue
.Note that
tColl.IsAssignableFrom(t.GetGenericTypeDefinition())
returnsfalse
for aList<int>
for example.I have tested all these combinations for
MyT o = new MyT();
Output:
GetGenericTypeDefinition
和typeof(Collection<>)
将完成这项工作:GetGenericTypeDefinition
andtypeof(Collection<>)
will do the job: