繁体   English   中英

c# 在 Switch Case 中使用枚举抛出异常

[英]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 ..只对给定语句的兴趣结果为truefalse ..)

在检查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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM