如何确定一个属性是否是数组类型。
示例:
public bool IsPropertyAnArray(PropertyInfo property)
{
// return true if type is IList<T>, IEnumerable<T>, ObservableCollection<T>, etc...
}
如何确定一个属性是否是数组类型。
示例:
public bool IsPropertyAnArray(PropertyInfo property)
{
// return true if type is IList<T>, IEnumerable<T>, ObservableCollection<T>, etc...
}
您似乎在问两个不同的问题:一个类型是否是数组(例如string[]
),或者任何集合类型。
对于前者,只需检查property.PropertyType.IsArray
。
对于后者,您必须决定要让类型符合的最低标准是什么。例如,您可以通过使用typeof(IEnumerable).IsAssignableFrom(property.PropertyType)
来检查非泛型的IEnumerable
。如果您知道T的实际类型,也可以将其用于通用接口,例如typeof(IEnumerable<int>).IsAssignableFrom(property.PropertyType)
。
如果不知道T的值,可以通过检查property.PropertyType.GetInterface(typeof(IEnumerable<>).FullName)
是否不为null
来检查通用的IEnumerable<T>
或任何其他通用接口。请注意,在该代码中,我没有为T
指定任何类型。您也可以对IList<T>
或任何其他感兴趣的类型执行相同的操作。
例如,如果要检查通用的IEnumerable<T>
,则可以使用以下内容:
public bool IsPropertyACollection(PropertyInfo property)
{
return property.PropertyType.GetInterface(typeof(IEnumerable<>).FullName) != null;
}
数组也实现了IEnumerable接口,因此它们也会从该方法返回true
。
String
类实现了 IEnumerable<char>
接口,因此符合这些标准可被视为一个集合。你需要具体地过滤它,或检查更具限制性的接口(例如 ICollection<T>
或 IList<T>
)。 - SvenIEnumerable<>
的类型也将成为非泛型的 IEnumerable
。 - Jeppe Stig Nielsen除了String
类以外,因为它实现了IEnumerable<char>
,所以也可以视为一种集合。
public bool IsPropertyACollection(this PropertyInfo property)
{
return (!typeof(String).Equals(property.PropertyType) &&
typeof(IEnumerable).IsAssignableFrom(property.PropertyType));
}
如果你想知道一个属性是否为数组,实际上非常简单:
property.PropertyType.IsArray;
编辑
如果您想知道它是否是实现了IEnumerable接口的类型,就像所有“集合类型”一样,也不是很复杂:
return property.PropertyType.GetInterface("IEnumerable") != null;
IList<T>
的自定义类型将从此属性返回 false。 - vgruIsSubclassOf
不适用于接口,只适用于基类。 - Sven public static bool IsGenericEnumerable(Type type)
{
return type.IsGenericType &&
type.GetInterfaces().Any(
ti => (ti == typeof (IEnumerable<>) || ti.Name == "IEnumerable"));
}
public static bool IsEnumerable(Type type)
{
return IsGenericEnumerable(type) || type.IsArray;
}
对我来说,以下内容无法正常工作,
return property.PropertyType.GetInterface(typeof(ICollection<>).FullName) != null;
以下代码曾经有效,
typeof(ICollection<>).IsAssignableFrom(property.PropertyType.GetGenericTypeDefinition())
这是一种快捷的方式来检查ICollection<IInterface>
或ICollection<BaseClassInTree>
var property = request as PropertyInfo;
property.PropertyType.IsGenericType && (typeof(ICollection<>).IsAssignableFrom(property.PropertyType.GetGenericTypeDefinition())) && typeof().IsAssignableFrom(property.PropertyType.GenericTypeArguments[0])
IEnumerable
而不是IEnumerator
? - vgru