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 语句
基础教程推荐
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
