c# - 如何判断某物是否为 IEnumerable<>?

标签 c# reflection ienumerable

我有一个类型。

我如何判断它是否是 IEnumerable<>

这些:

typeof(IEnumerable<>).IsAssignableFrom(memberType);
typeof(IEnumerable<object>).IsAssignableFrom(memberType);

对于 IEnumerable<int> 返回 false

鉴于此:

typeof(IEnumerable).IsAssignableFrom(memberType);

对字符串返回 true。

最佳答案

反射(reflection)很有趣;旁注:请记住,您可以实现 IEnumerable<X> IEnumerable<Y> (等)在同一类型上,所以为了简单起见,我只是报告第一个发现的任意:

static void Main()
{
    Console.WriteLine(FindFirstIEnumerable(typeof(int))); // null
    Console.WriteLine(FindFirstIEnumerable(typeof(string))); // System.Char
    Console.WriteLine(FindFirstIEnumerable(typeof(Guid[]))); // System.Guid
    Console.WriteLine(FindFirstIEnumerable(typeof(IEnumerable<float>))); // System.Single
}

static Type FindFirstIEnumerable(Type type)
{
    if (type == null || !typeof(IEnumerable).IsAssignableFrom(type))
        return null; // anything IEnumerable<T> *must* be IEnumerable
    if (type.IsInterface && type.IsGenericType
        && type.GetGenericTypeDefinition() == typeof(IEnumerable<>))
    {
        return type.GetGenericArguments()[0];
    }
    foreach(var iType in type.GetInterfaces())
    {
        if (iType.IsGenericType &&
            iType.GetGenericTypeDefinition() == typeof(IEnumerable<>))
        {
            return iType.GetGenericArguments()[0];
        }
    }
    return null;
}

关于c# - 如何判断某物是否为 IEnumerable<>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58226119/

相关文章:

c# - 使用 Json 错误请求的 WCF 服务

.net - 获取不带 "Attribute"的属性类型名称

c# - 从通用列表中删除一个元素

c# - 从数据表插入数据表

c# - 更改类的默认值

c# - 从单页中删除布局

c# - 如何在 MSAL .Net C# 中获取刷新 token

c# - Resharper - 在 C# 中使用 'help' 快捷方式时禁用 "prop"

c# - 使用包含变量名称的字符串访问变量

java - 如何访问 Java 中自定义注释中定义的字段