繁体   English   中英

确定Type是枚举类型的通用列表

[英]Determine if a Type is a Generic List of Enum Types

我需要确定给定类型是否为枚举类型的通用列表。

我想出了以下代码:

void Main()
{
    TestIfListOfEnum(typeof(int));
    TestIfListOfEnum(typeof(DayOfWeek[]));
    TestIfListOfEnum(typeof(List<int>));
    TestIfListOfEnum(typeof(List<DayOfWeek>));
    TestIfListOfEnum(typeof(List<DayOfWeek>));
    TestIfListOfEnum(typeof(IEnumerable<DayOfWeek>));
}

void TestIfListOfEnum(Type type)
{
    Console.WriteLine("Object Type: \"{0}\", List of Enum: {1}", type, IsListOfEnum(type));
}

bool IsListOfEnum(Type type)
{
    var itemInfo = type.GetProperty("Item");
    return (itemInfo != null) ? itemInfo.PropertyType.IsEnum : false;
}

这是上面代码的输出:

Object Type: "System.Int32", List of Enum: False
Object Type: "System.DayOfWeek[]", List of Enum: False
Object Type: "System.Collections.Generic.List`1[System.Int32]", List of Enum: False
Object Type: "System.Collections.Generic.List`1[System.DayOfWeek]", List of Enum: True
Object Type: "System.Collections.Generic.List`1[System.DayOfWeek]", List of Enum: True
Object Type: "System.Collections.Generic.IEnumerable`1[System.DayOfWeek]", List of Enum: False

除了最后一个例子,所有输出正是我想要的。 它不会检测到typeof(IEnumerable<DayOfWeek>)是枚举类型的集合。

有谁知道我在最后一个例子中如何检测枚举类型?

如果你想测试它,给定一个类型,那么它是IEnumerable<T>类型,其中Tenum ,你可以做以下。

首先,一种获取可枚举枚举类型的方法:

    public static IEnumerable<Type> GetEnumerableTypes(Type type)
    {
        if (type.IsInterface)
        {
            if (type.IsGenericType
                && type.GetGenericTypeDefinition() == typeof(IEnumerable<>))
            {
                yield return type.GetGenericArguments()[0];
            }
        }
        foreach (Type intType in type.GetInterfaces())
        {
            if (intType.IsGenericType
                && intType.GetGenericTypeDefinition() == typeof(IEnumerable<>))
            {
                yield return intType.GetGenericArguments()[0];
            }
        }
    }

接着:

    public static bool IsEnumerableOfEnum(Type type)
    {
        return GetEnumerableTypes(type).Any(t => t.IsEnum);
    }

您可以像这样获取IEnumerable<T>的类型:

Type enumerableType = enumerable.GetType().GenericTypeArguments[0];

那么你可以通过检查是否可以将类型分配给Enum类型的变量( Enum的基类)来测试它是否是枚举:

typeof(Enum).IsAssignableFrom(enumerableType)

这是一个简单的方法:

public static bool TestIfSequenceOfEnum(Type type)
{
    return (type.IsInterface ? new[] { type } : type.GetInterfaces())
        .Where(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IEnumerable<>))
        .Any(i => i.GetGenericArguments().First().IsEnum);
}

基本上,提取由该类型实现的所有接口,找到所有IEnumerable<T> ,如果这些T中的任何一个是枚举,则返回true 记住一个具体的类可以多次实现IEnumerable<T> (使用不同的T )。

如果type是类或者它是接口,这都适用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM