枚举与具有静态成员的常量/类?
我有一组特定于应用程序的代码(代码与其名称的一对一映射),并且我一直在 C# 中使用枚举来表示它们。我现在不确定这是否有必要。这些值永远不会改变,并且它们总是与这些标签相关联:
Workflow_Status_Complete = 1
Workflow_Status_Stalled = 2
Workflow_Status_Progress = 3
Workflow_Status_Complete = 4
Workflow_Status_Fail = 5
我应该使用枚举还是具有静态成员的类?
I have a set of codes that are particular to the application (one to one mapping of the code to its name), and I've been using enums in C# to represent them. I'm not sure now if that is even necessary. The values never change, and they are always going to be associated with those labels:
Workflow_Status_Complete = 1
Workflow_Status_Stalled = 2
Workflow_Status_Progress = 3
Workflow_Status_Complete = 4
Workflow_Status_Fail = 5
Should I use an enum or a class with static members?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
对我来说,int 类型的静态成员似乎不如枚举。你失去了枚举的类型安全性。调试时您看不到符号名称,而只是一个数字。
另一方面,如果条目不仅仅包含名称/整数值对,那么类可能是一个好主意。但这些字段应该是该类的而不是 int 的。像这样的东西:
Static members of type int seems to be inferior to an enum to me. You lose the typesafety of an enum. And when debugging you don't see the symbolic name but just a number.
On the other hand if an entry consists of more than just a name/integervalue pair a class can be a good idea. But then the fields should be of that class and not int. Something like:
使用枚举。即使您的代码从未改变,仅通过检查也很难知道该值代表什么。使用枚举的众多优点之一。
即使是调试器也无法为您提供太多帮助,尤其是在有许多不同值的情况下。
Use an enum. Even though your codes never change, it will be difficult to know what the value represents just by inspection. One of the many strengths of using enums.
Not even the debugger will help you much here, especially if there are many different values.
查看状态模式,因为这是一个更好的设计。按照您正在使用的想法,您最终会得到一个很大的 switch/if-else 语句,这可能很难跟上。
Check out the State Pattern as this is a better design. With the idea you are using you'll end up with a large switch/if-else statement which can be very difficult to keep up.
我倾向于枚举,因为它们提供了更多信息,并且它们使您的代码“更容易正确使用,并且很难错误使用”。 (我认为这句话来自《务实的程序员》。
I would lean towards enums as they provide more information and they make your codes "easier to use correctly and difficult to use incorrectly". (I think the quote is from The Pragmatic Programmer.