[英]How to check if an enum is of certain type in c#?
我有一個通用的 function 接收一個參數類型 T ,它被強制為一個結構。 我想知道如何檢查是否聲明了某種 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
的類型完全無關。 它相當於:
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,或者可能是 static Dictionary<Type, Action>
,但如果不了解更多關於真實場景的信息,就很難說。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.