Как определить, является ли тип 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 ответа

Решение

Попробуй это:

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)

Проверьте метод 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) против b.IsAssignableFrom(a)!

@BartoszKP имеет правильный ответ.

Другие вопросы по тегам