1

有没有办法检查是否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);

但它不起作用。有任何想法吗?

4

2 回答 2

2

查看方法Type.IsAssignableFrom

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

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

@BartoszKP 有正确的答案。

于 2013-08-16T14:43:43.077 回答
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

于 2013-08-16T16:49:50.457 回答