简体   繁体   中英

How to check if an enum is of certain type in c#?

I have a generic function that receives a parameter type T which is forced to be an struct. I would like to know how do I check if that type of of certain Enum type declared, I'm doing something like this:

public static string GetSomething<T>() where T : struct
        {
                switch (typeof(T))
                {
                    case Type EnumTypeA when EnumTypeA == typeof(T):
                        Console.WriteLine("is EnumTypeA");
                        break;
                    case Type EnumTypeB when EnumTypeB == typeof(T):
                        Console.WriteLine("is EnumTypeB");
                        break;
                    default:
                        Type type = typeof(T);
                        return new Exception($"Unsupported type {Type.GetTypeCode(type)}");
                }

        }

But i'm getting always EnumTypeA even when I send EnumTypeB

This is ideally what I would like to do:

                switch (typeof(T))
                {
                    case is EnumTypeA
                        Console.WriteLine("is EnumTypeA");
                        break;
                    case is EnumTypeB
                        Console.WriteLine("is EnumTypeB");
                        break;
                    default:
                        Type type = typeof(T);
                        return new Exception($"Unsupported type {Type.GetTypeCode(type)}");
                }

Look at this case:

case Type EnumTypeA when EnumTypeA == typeof(T):

That will always be true (because you're switching on typeof(T) ), and it's unrelated to the type called EnumTypeA at all. It's equivalent to:

case Type t when t == typeof(T):

What you actually want is:

case Type t when t == typeof(EnumTypeA):

So something like this:

switch (typeof(T))
{
    case Type t when t == typeof(EnumTypeA):
        Console.WriteLine("is EnumTypeA");
        break;
    case Type t when t == typeof(EnumTypeB):
        Console.WriteLine("is EnumTypeB");
        break;
    default:
        Type type = typeof(T);
        return new Exception($"Unsupported type {Type.GetTypeCode(type)}");
}

Personally I'd probably prefer to use if/else for this situation, or possibly a static Dictionary<Type, Action> , but it's hard to say without knowing more about the real scenario.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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