【问题标题】:How can I know if a propertyInfo is of the type IList in C#?如何知道 propertyInfo 是否属于 C# 中的 IList 类型?
【发布时间】:2015-02-14 03:45:32
【问题描述】:

鉴于这个类:

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() 以上所有内容。我该如何解决这个问题?

【问题讨论】:

  • 我注意到您在某些示例中使用 IsAssignableFrom 向后使用 DotNetFiddleExample
  • a3 应该返回 true。

标签: c# reflection


【解决方案1】:

您可以使用GetGenericTypeDefinition

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

这将为所有 IList&lt;&gt; 类型返回 true。如果您想检查其他类型(ICollectionIEnumerable 等),您也可以对它们进行相同的检查。

【讨论】:

  • 但这会失败,imo,在具有不同属性的类上。 GetGenericTypeDefinition(..) 只能在泛型类型属性上调用,在其他类型属性上会引发异常。需要安全检查。
  • @Tigran 你是对的,感谢您指出这一点。我添加了检查以确保类型是通用的。
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    Console.WriteLine("Is IList:" + (new List()).GetType().GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IList) ));

    来自这个问题:How to determine if a type implements an interface with C# reflection

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多