如何知道 propertyInfo 是否属于 C# 中的 IList 类型?

Dan*_*cco 2 c# reflection

鉴于这个类:

public class SomeClass
{
    public int SomeProperty { get; set; }
    public IList<AnotherClass> MyList { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

而这段代码:

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?
}
Run Code Online (Sandbox Code Playgroud)

我尝试过的事情:

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
Run Code Online (Sandbox Code Playgroud)

加上以上所有与PropertyType.GetType(). 我怎么能弄明白呢?

Sel*_*enç 5

您可以使用 GetGenericTypeDefinition

if(properties[i].PropertyType.IsGenericType &&
   properties[i].PropertyType.GetGenericTypeDefinition() == typeof(IList<>))
Run Code Online (Sandbox Code Playgroud)

这将返回真正的所有IList<>types.If你要检查是否有其他人,( ICollectionIEnumerable等等),你可以为他们做相同的检查为好。