给定这个类:
public class SomeClass
{
public int SomeProperty { get; set; }
public IList<AnotherClass> MyList { get; set; }
}
还有这段代码:
SomeClass myClass = new SomeClass();
PropertyInfo[] properties = myClass.GetType().GetProperties();
for(int i = 0; i < properties.Length; i++)
{
//How can I figure that the current property is a collection/list?
}
我尝试过的事情:
bool a1 = properties[i].PropertyType.IsAssignableFrom(typeof(IList));
//false
bool a2 = properties[i].PropertyType.IsAssignableFrom(typeof(IList<>));
//false
bool a3 = typeof(IList).IsAssignableFrom(properties[i].PropertyType);
//false
bool a4 = typeof(IList<>).IsAssignableFrom(properties[i].PropertyType);
//false
bool a5 = properties[i].PropertyType.Equals(typeof(IList));
//false
bool a6 = properties[i].PropertyType.Equals(typeof(IList<>));
//false
bool a7 = properties[i].PropertyType.IsSubclassOf(typeof(IList));
//false
bool a8 = properties[i].PropertyType.IsSubclassOf(typeof(IList<>));
//false
bool a9 = properties[i].PropertyType is IList;
//false
bool a0 = typeof(ICollection<>).IsAssignableFrom(properties[i].PropertyType);
//false
用 PropertyType.GetType() 加上以上所有内容。我该如何解决这个问题?
请您参考如下方法:
您可以使用 GetGenericTypeDefinition
if(properties[i].PropertyType.IsGenericType &&
properties[i].PropertyType.GetGenericTypeDefinition() == typeof(IList<>))
这将为所有 IList<> 返回 true types.If you want to check for others, ( ICollection , IEnumerable etc.) 你也可以对他们做同样的检查。
