确定是否一个属性是一种反射阵列 [英] Determine if a property is a kind of array by reflection
问题描述
我怎么能确定一个属性是一个类型的数组
例如:
如果类型是IList的<公共BOOL IsPropertyAnArray(的PropertyInfo财产)
{
//返回true; T> ;,的IEnumerable< T> ;,的ObservableCollection< T> ;,等..
}
您似乎是问两个不同问题:一个类型是一个数组(如的String []
)或任何集合类型
有关前者。 ,只需检查 property.PropertyType.IsArray
。
对于后者,你必须决定什么是最低标准你想一个类型符合。例如,您可以通过使用 typeof运算(IEnumerable的).IsAssignableFrom(property.PropertyType)
的IEnumerable >。您也可以使用这个泛型接口,如果你知道实际类型T的,例如的typeof(IEnumerable的< INT>)。IsAssignableFrom(property.PropertyType)
检查一般的IEnumerable< T>
或不知道T的值的任何其他通用接口,可通过检查来完成,如果 property.PropertyType.GetInterface(typeof运算(IEnumerable的<>) .FullName)
不是空
。请注意,我没有指定在该代码的任何类型 T
。您可以为的IList<这样做; T>
或任何其他类型你有兴趣
例如。你可以使用下面的,如果你想检查一般的IEnumerable< T>
:
公共BOOL IsPropertyACollection(的PropertyInfo财产)
{
返回property.PropertyType.GetInterface(typeof运算(IEnumerable的<方式>)全名)!= NULL;
}
阵列还实现IEnumerable,所以他们也将返回真正
从该方法。
How can I determine if a property is a kind of array.
Example:
public bool IsPropertyAnArray(PropertyInfo property)
{
// return true if type is IList<T>, IEnumerable<T>, ObservableCollection<T>, etc...
}
You appear to be asking two different questions: whether a type is an array (e.g. string[]
) or any collection type.
For the former, simply check property.PropertyType.IsArray
.
For the latter, you have to decide what is the minimum criteria you want a type to conform to. For example, you could check for the non-generic IEnumerable
by using typeof(IEnumerable).IsAssignableFrom(property.PropertyType)
. You can also use this for generic interfaces if you know the actual type of T, e.g. typeof(IEnumerable<int>).IsAssignableFrom(property.PropertyType)
.
Checking for the generic IEnumerable<T>
or any other generic interface without knowing the value of T can be done by checking if property.PropertyType.GetInterface(typeof(IEnumerable<>).FullName)
is not null
. Note that I didn't specify any type for T
in that code. You can do the same for IList<T>
or any other type you're interested in.
For example you could use the following if you want to check for the generic IEnumerable<T>
:
public bool IsPropertyACollection(PropertyInfo property)
{
return property.PropertyType.GetInterface(typeof(IEnumerable<>).FullName) != null;
}
Arrays also implement IEnumerable, so they will also return true
from that method.
这篇关于确定是否一个属性是一种反射阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!