[英]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.