When to use enums, and when to replace them with a class with static members?

后端 未结 6 1058
情话喂你
情话喂你 2020-11-29 02:16

It recently occured to me that the following (sample) enumeration...

enum Color
{
    Red,
    Green,
    Yellow,
    Blue
}

... could be r

6条回答
  •  旧巷少年郎
    2020-11-29 02:32

    Both approaches are valid. You should choose per case.

    I can add that enums support bit operations as flags (there's even [Flags] attribute to support this semantics and produce pretty strings from enums).

    There's a very similar refactoring named Replacing Enums with the Strategy Pattern. Well, in your case it's not quite complete, since your Color is passive and does not act like a strategy. However, why not think of it as a special case?

提交回复
热议问题