简体   繁体   English

Enum vs Constants / Class with Static Members?

[英]Enum vs Constants/Class with Static Members?

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. 我有一组特定于应用程序的代码(代码与其名称的一对一映射),并且我一直在使用C#中的枚举来表示它们。 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? 我应该使用带有静态成员的枚举或类吗?

Static members of type int seems to be inferior to an enum to me. int类型的静态成员似乎不如我的枚举。 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. 但是那些字段应该属于那个类,而不是int。 Something like: 就像是:

class MyFakeEnum
{
   public static readonly MyFakeEnum Value1=new MyFakeEnum(...);
}

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. 使用枚举的众多优势之一。

enum RealEnum : uint
{
    SomeValue = 0xDEADBEEF,
}
static class FakeEnum
{
    public const uint SomeValue = 0xDEADBEEF;
}

var x = RealEnum.SomeValue;
var y = FakeEnum.SomeValue;
// what's the value?
var xstr = x.ToString(); // SomeValue
var ystr = y.ToString(); // 3735928559

Not even the debugger will help you much here, especially if there are many different values. 甚至调试器也不会对你有所帮助,特别是如果有许多不同的值。

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. 根据您使用的想法,您将最终得到一个很大的开关/ if-else语句,这可能很难跟上。

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. (我认为引用来自实用程序员。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM