c# - 使用反射检查属性是否仅为引用类型的 IEnumerable 而不是字符串或值类型

标签 c# reflection

您好,我需要使用反射检查属性是否为 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/

相关文章:

c# - Type.GetType(string) 使用 "Generic<T>"语法?

java - 如何在方法中获取参数值的完全限定名称

c# - Microsoft Bot Framework - 如何知道用户时间和 IP 以跟踪位置

c# - 正则表达式字符串,但有几个选项

c# - 如何使用反射获取 ValueType 类型的默认值

java - 在运行时检查类是否具有使用泛型的特定构造函数

c++ - 如何使用 C++ 模板模拟类型引用?

c# - Azure .NET MVC 核心应用程序 : User not being redirected upon form submission

c# - TextBlock TextWrapping Wrap 和 NoWrap 相结合,通过 DynamicResource 文本

c# - 如何使用ollydbg查找应用程序的功能?