[英]c# Using enum in Switch Case throwing exception
我正在開發 .NET 6.0 應用程序,我嘗試在 switch 中使用枚舉來與字符串值進行比較,但出現異常。
error
private static bool ValidateAlphanumericCase(string text, string fieldName)
{
if (!string.IsNullOrWhiteSpace(fieldName))
{
var rule = GetRule(fieldName).TxtFieldFormat; // string value
switch (rule)
{
case TextFieldFormat.AlphanumericUpperCase.ToString():
break;
case TextFieldFormat.AlphanumericLowerCase.ToString():
break;
}
}
else
{
new EmptyFieldNameException();
}
return false;
}
enum
public enum TextFieldFormat
{
AlphanumericUpperCase = 0,
AlphanumericLowerCase = 1,
}
TextFieldFormat.AlphanumericUpperCase.ToString()
這是一個方法調用表達式,它不是 swith 語句的有效模式。
您可以在此處找到所有有效模式: https ://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/patterns
最接近的模式是類型模式或常量模式,我猜編譯器將AlphanumericUpperCase
識別為TextFieldFormat
的嵌套類並失敗。
在這種情況下,您可以使用 nameof 運算符。
switch (rule)
{
case nameof(TextFieldFormat.AlphanumericUpperCase):
break;
case nameof(TextFieldFormat.AlphanumericLowerCase):
break;
}
似乎您對switch-case
塊的理解有所不同。
switch
塊只是許多if - else if - else
塊的快捷方式(但更高效的快捷方式)。 當然它們不一樣,但它們的工作邏輯幾乎是一樣的。
通過這些非常少的信息,您可以輕松地思考代碼中的問題。
賓果,你是對的! Case
塊應該檢查狀態。 ( Boolean
..只對給定語句的興趣結果為true
或false
..)
在檢查boolean
結果后,which case
的語句匹配,代碼在那個case
塊上繼續。
因此,在您的情況下,您的代碼可能是這樣的:
switch (rule)
{
/// Some statements need to put in paranthesis. Also you would need put business codes of cases into curly braces.
/// I write from my mind.
/// So please try paranthesis and/or braces if this code break.
case rule==TextFieldFormat.AlphanumericUpperCase.ToString():
DoSomethingWithFirstCase(); break;
case rule==TextFieldFormat.AlphanumericLowerCase.ToString():
DoSomethingWitSecondCase(); break;
default: DoSomethingWhenNoMatchWithOtherCases();
}
希望這可以幫助。
你也可以這樣使用
TextFieldFormat.AlphanumericUpperCase.ToString("g" or "G")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.