我需要知道类中属性的类型是否是使用PropertyInfo类的泛型集合(List,ObservableCollection)。我怎么知道一个属性是否是一个通用集合
foreach (PropertyInfo p in (o.GetType()).GetProperties())
{
if(p is Collection<T> ?????)
}
我需要知道类中属性的类型是否是使用PropertyInfo类的泛型集合(List,ObservableCollection)。我怎么知道一个属性是否是一个通用集合
foreach (PropertyInfo p in (o.GetType()).GetProperties())
{
if(p is Collection<T> ?????)
}
GetGenericTypeDefinition
和typeof(Collection<>)
将做的工作:
if(p.PropertyType.IsGenericType && typeof(Collection<>).IsAssignableFrom(p.PropertyType.GetGenericTypeDefinition())
Type tColl = typeof(ICollection<>);
foreach (PropertyInfo p in (o.GetType()).GetProperties()) {
Type t = p.PropertyType;
if (t.IsGenericType && tColl.IsAssignableFrom(t.GetGenericTypeDefinition()) ||
t.GetInterfaces().Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == tColl)) {
Console.WriteLine(p.Name + " IS an ICollection<>");
} else {
Console.WriteLine(p.Name + " is NOT an ICollection<>");
}
}
你需要测试t.IsGenericType
和x.IsGenericType
,否则,如果该类型不是通用GetGenericTypeDefinition()
会抛出异常。
如果该物业被宣布为ICollection<T>
那么tColl.IsAssignableFrom(t.GetGenericTypeDefinition())
将返回true
。
如果属性声明为它实现ICollection<T>
一个类型,然后 t.GetInterfaces().Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == tColl)
将返回true
。
请注意,例如tColl.IsAssignableFrom(t.GetGenericTypeDefinition())
返回false
为List<int>
。
我已经测试所有这些组合为MyT o = new MyT();
private interface IMyCollInterface1 : ICollection<int> { }
private interface IMyCollInterface2<T> : ICollection<T> { }
private class MyCollType1 : IMyCollInterface1 { ... }
private class MyCollType2 : IMyCollInterface2<int> { ... }
private class MyCollType3<T> : IMyCollInterface2<T> { ... }
private class MyT
{
public ICollection<int> IntCollection { get; set; }
public List<int> IntList { get; set; }
public IMyCollInterface1 iColl1 { get; set; }
public IMyCollInterface2<int> iColl2 { get; set; }
public MyCollType1 Coll1 { get; set; }
public MyCollType2 Coll2 { get; set; }
public MyCollType3<int> Coll3 { get; set; }
public string StringProp { get; set; }
}
输出:
IntCollection IS an ICollection<>
IntList IS an ICollection<>
iColl1 IS an ICollection<>
iColl2 IS an ICollection<>
Coll1 IS an ICollection<>
Coll2 IS an ICollection<>
Coll3 IS an ICollection<>
StringProp is NOT an ICollection<>
你不应该对测试类似'ICollection的'而不是'收集'?许多通用集合(例如'List ')不会继承自“Collection ”。 –
LukeH
2009-10-15 08:53:05
'p.GetType()'将返回一个'Type'来描述'RuntimePropertyInfo'而不是属性的类型。 'GetGenericTypeDefinition()'也会为非泛型类型引发异常。 – 2012-01-14 17:54:45
准确地说,GetGenericTypeDefinition为非泛型类型引发异常。 – Shaggydog 2014-08-08 14:16:10