简体   繁体   English

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

[英]c# Using enum in Switch Case throwing exception

I am working on .NET 6.0 application, I have enum that I am trying to use in switch as to compare with string value but getting 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()

This is a method invocation expression and it is not a valid pattern for swith statement.这是一个方法调用表达式,它不是 swith 语句的有效模式。

You can find all valid patterns here: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/patterns您可以在此处找到所有有效模式: https ://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/patterns

The closest pattern is type pattern or constant pattern, I guess the compiler recognizes AlphanumericUpperCase as a nested class of TextFieldFormat and fails.最接近的模式是类型模式或常量模式,我猜编译器将AlphanumericUpperCase识别为TextFieldFormat的嵌套类并失败。

In this case you can use nameof operator.在这种情况下,您可以使用 nameof 运算符。

 switch (rule)
 {
      case nameof(TextFieldFormat.AlphanumericUpperCase):
          break;
      case nameof(TextFieldFormat.AlphanumericLowerCase):
          break;
 }

Seems you understood switch-case block a little bit different.似乎您对switch-case块的理解有所不同。

A switch block is simply a shortcut (but more performant shortcut) of many if - else if - else blocks. switch块只是许多if - else if - else块的快捷方式(但更高效的快捷方式)。 Of course they are not the same, but their working logic almost the same.当然它们不一样,但它们的工作逻辑几乎是一样的。

With this very little info, you can easily think about what's wrong in your code.通过这些非常少的信息,您可以轻松地思考代码中的问题。

Bingo, you're right!宾果,你是对的! Case blocks should check the state. Case块应该检查状态。 ( Boolean value..Just interests with either the given statement results true or false ..) Boolean ..只对给定语句的兴趣结果为truefalse ..)

After checking the boolean result, Which case 's statement match, code continues on that case block.在检查boolean结果后,which case的语句匹配,代码在那个case块上继续。

So, in your situation your code could be like this :因此,在您的情况下,您的代码可能是这样的:

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();
}

Hope this helps.希望这可以帮助。

你也可以这样使用

TextFieldFormat.AlphanumericUpperCase.ToString("g" or "G")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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