c# - 如何检查枚举是否是某种类型的c#?

lov*_*ode 1 .net c#

我有一个通用函数,它接收一个参数类型 T,它被强制为一个 struct 。我想知道如何检查是否声明了某种 Enum 类型的类型,我正在做这样的事情:

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)}");
                }

        }
Run Code Online (Sandbox Code Playgroud)

但即使我发送 EnumTypeB,我也总是得到 EnumTypeA

理想情况下,这是我想要做的:

                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)}");
                }
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 6

看看这个案例:

case Type EnumTypeA when EnumTypeA == typeof(T):
Run Code Online (Sandbox Code Playgroud)

这将始终是正确的(因为您正在打开typeof(T)),并且它与调用的类型EnumTypeA完全无关。它相当于:

case Type t when t == typeof(T):
Run Code Online (Sandbox Code Playgroud)

真正想要的是:

case Type t when t == typeof(EnumTypeA):
Run Code Online (Sandbox Code Playgroud)

所以像这样:

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)}");
}
Run Code Online (Sandbox Code Playgroud)

就我个人而言,我可能更喜欢在这种情况下使用 if/else ,或者可能是 static Dictionary<Type, Action>,但是如果不了解更多真实情况就很难说。