我怎么知道propertyInfo是否属于C#中的IList类型?

时间:2014-12-15 22:28:51

标签: c# reflection

鉴于此课程:

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()的所有上述内容。我怎么能搞清楚这一点?

3 个答案:

答案 0 :(得分:4)

您可以使用GetGenericTypeDefinition

if(properties[i].PropertyType.IsGenericType &&
   properties[i].PropertyType.GetGenericTypeDefinition() == typeof(IList<>))

这将为所有IList<>类型返回 true 。如果您想检查其他人,(ICollectionIEnumerable等等,您也可以这样做检查它们。

答案 1 :(得分:1)

您可以使用 System.Collection.IList 变体:

        public static bool IsIList(this Type type)
        {
            return type.GetInterfaces().Contains(typeof(System.Collections.IList));
        }

答案 2 :(得分:0)

Console.WriteLine(“是IList:” +(新List())。GetType()。GetInterfaces()。Any(i => i.IsGenericType && i.GetGenericTypeDefinition()== typeof(IList <>) ));

此问题:How to determine if a type implements an interface with C# reflection