如何判断ParameterInfo类型是否为集合?

时间:2013-08-16 14:38:08

标签: c# icollection gettype parameterinfo

有没有办法检查ParameterInfo是否是收藏品?

我试过这个:

ConstructorInfo[] constructorInfos = typeof(T).GetConstructors();
ConstructorInfo constructorInfo = constructorInfos[0];
ParameterInfo[] paramsVar = constructorInfo.GetParameters();
IEnumerable<ParameterInfo> collectionParams = paramsVar.Where(
    x => x.ParameterType.GetElementType() is ICollection);

但它不起作用。有什么想法吗?

2 个答案:

答案 0 :(得分:2)

查看方法Type.IsAssignableFrom

    ConstructorInfo [] constructorInfos = typeof(T)。GetConstructors();     ConstructorInfo constructorInfo = constructorInfos [0];     ParameterInfo [] paramsVar = constructorInfo.GetParameters();     IEnumerable collectionParams = paramsVar.Where(         x =&gt; x.ParameterType.GetElementType()IsAssignableFrom(typeof运算(ICollection的)))。

很容易混淆a.IsAssignableFrom(b)b.IsAssignableFrom(a)

@BartoszKP有right answer.

答案 1 :(得分:2)

试试这个:

ConstructorInfo[] constructorInfos = typeof(T).GetConstructors();
ConstructorInfo constructorInfo = constructorInfos[0];
ParameterInfo[] paramsVar = constructorInfo.GetParameters();
IEnumerable<ParameterInfo> collectionParams = paramsVar.Where(
    x => typeof(ICollection).IsAssignableFrom(x.ParameterType));

(请注意,我已移除GetElementType来电,并已切换typeof(ICollection)x.ParameterType