如何解决如何检查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)}");
}
}
但是即使我发送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)}");
}
解决方法
看看这种情况:
case Type EnumTypeA when EnumTypeA == typeof(T):
总是是正确的(因为您要打开typeof(T)
),并且它与名为EnumTypeA
的 type 完全无关。等效于:
case Type t when t == typeof(T):
您实际上想要的是:
case Type t when t == typeof(EnumTypeA):
是这样的:
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)}");
}
我个人会大概更愿意在这种情况下使用if / else,或者可能是静态的Dictionary<Type,Action>
,但是很难说出它对真实情况的了解。>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。