使用带有常量或枚举的 switch 语句? (哪个更好)? C#
嗨,我有一个简单的问题,但这个问题已经困扰我一段时间了。
问题:
在 C# 中使用 switch 语句时,使用枚举
是否比使用常量
更好,反之亦然?或者这是一个偏好问题?我问这个问题是因为很多人似乎喜欢使用 enum
,但是当您打开 int
值时,您必须强制转换 中包含的每个值enum
转换为 int
,即使您指定了 enum
的类型。
代码片段:
class Program
{
enum UserChoices
{
MenuChoiceOne = 1,
MenuChoiceTwo,
MenuChoiceThree,
MenuChoiceFour,
MenuChoiceFive
}
static void Main()
{
Console.Write("Enter your choice: ");
int someNum = int.Parse(Console.ReadLine());
switch (someNum)
{
case (int)UserChoices.MenuChoiceOne:
Console.WriteLine("You picked the first choice!");
break;
// etc. etc.
}
}
}
是否有某种方法可以创建 enum
的实例,并将整个 enum
转换为 int?
谢谢!
HI, I've got a simple question, but one that has been bugging me for a while.
Question:
When using switch statements in C#, is it considered better practice to use enums
over constants
or vice versa? Or is it a matter of preference? I ask this because many people seem to like using enums
, but when you are switching on an int
value, you have to cast each of the values contained in the enum
to an int
, even if you specify the type of enum
.
Code Snippet:
class Program
{
enum UserChoices
{
MenuChoiceOne = 1,
MenuChoiceTwo,
MenuChoiceThree,
MenuChoiceFour,
MenuChoiceFive
}
static void Main()
{
Console.Write("Enter your choice: ");
int someNum = int.Parse(Console.ReadLine());
switch (someNum)
{
case (int)UserChoices.MenuChoiceOne:
Console.WriteLine("You picked the first choice!");
break;
// etc. etc.
}
}
}
Is there some way you can create an instance of the enum
and just cast the whole enum
to an int?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为什么不这样做呢?
那么你只需要施放一次。
更新:修复了代码中的错误!
Why not do this instead?
Then you only need to cast once.
Update: fixed bug in code!
我认为枚举优于常量是因为可读性而不是因为性能。我发现在代码中读取枚举(一般而言,不仅仅是在 switch 语句中)比读取/理解常量及其用法更容易。
顺便说一句,你不必投射所有情况,你可以只投射你的开关。
I think the preference of enums over constants is because of readability and not because of performance. I find it easier to read enums in code (in general and not just in switch statements), than to read/understand constants and their usage.
and btw, you don't have to cast every case, you can just cast your switch.
我相信你可以简单地这样做:
I believe you can simply do: