我有一个通用函数,它接收一个参数类型 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)