您好,我需要使用反射检查属性是否为 IEnumerable
类型但不是字符串和值类型的 IEnumerable,而是非字符串引用类型的 IEnumerable。
现在我有那部分代码:
private bool IsEnumerable(PropertyInfo propertyInfo)
{
return propertyInfo.PropertyType.GetInterfaces().Contains(typeof(IEnumerable)) &&
propertyInfo.PropertyType != typeof(string);
}
如果属性是 IEnumerable<MyCustomType>
这没关系,但如果它是 IEnumerable<string>
我的方法应该返回 false。
最佳答案
您可以检查 GenericTypeArguments已实现的 IEnumerable<T>
类型上的接口(interface)以确保它既不是字符串类型也不是值类型:
public static bool IsEnumerable(PropertyInfo propertyInfo)
{
var propType = propertyInfo.PropertyType;
var ienumerableInterfaces = propType.GetInterfaces()
.Where(x => x.IsGenericType && x.GetGenericTypeDefinition() ==
typeof(IEnumerable<>)).ToList();
if (ienumerableInterfaces.Count == 0) return false;
return ienumerableInterfaces.All(x =>
x.GenericTypeArguments[0] != typeof(string) &&
!x.GenericTypeArguments[0].IsValueType);
}
这个更新版本适本地处理了多个 IEnumerable<T>
的情况。定义,其中没有 IEnumerable<T>
定义,并且通用实现类的类型与已实现的类型参数不匹配 IEnumerable<T>
.
关于c# - 使用反射检查属性是否仅为引用类型的 IEnumerable 而不是字符串或值类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39878768/