Switch statement with static fields(带有静态字段的 switch 语句)
问题描述
假设我有一堆静态字段,我想在 switch 中使用它们:
Suppose I have a bunch of static fields and I want to use them in switch:
public static string PID_1 = "12";
public static string PID_2 = "13";
public static string PID_3 = "14";
switch(pid)
{
case PID_1:
//Do something 1
break;
case PID_2:
//Do something 2
break;
case PID_3:
//Do something 3
break;
default:
//Do something default
break;
}
由于 C# 不允许在 switch 中使用非常量语句.我想了解这种设计的意图是什么.我应该如何在 c# 中执行上述操作?
Since C# doesn't allow non-const statement inside switch. I want to understand what is the intention of this kind of design. How should I do something like above in c#?
推荐答案
看起来那些字符串值应该只是常量.
It looks like those string values should simply be constant.
public const string PID_1 = "12";
public const string PID_2 = "13";
public const string PID_3 = "14";
如果这不是一个选项(它们实际上是在运行时更改的),那么您可以将该解决方案重构为一系列 if/else if 语句.
If that's not an option (they are actually changed at runtime), then you can refactor that solution into a series of if/else if statements.
关于为什么 case 语句需要保持不变;通过让它们保持不变,可以对语句进行更多优化.它实际上比一系列 if/else if 语句更有效(尽管如果您没有 lots 需要很长时间的条件检查,效果并不明显).它将生成一个等效的哈希表,其中 case 语句的值作为键.如果值可以更改,则无法使用该方法.
As to why the case statements need to be constant; by having them be constant it allows the statement to be much more heavily optimized. It is actually more efficient than a series of if/else if statements (although not dramatically so if you don't have lots of conditional checks that take a long time). It will generate the equivalent of a hash table with the case statement values as keys. That approach couldn't be used if the values can change.
这篇关于带有静态字段的 switch 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:带有静态字段的 switch 语句
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 输入按键事件处理程序 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01