Extending an enum via inheritance

后端 未结 15 2465
温柔的废话
温柔的废话 2020-11-27 17:40

I know this rather goes against the idea of enums, but is it possible to extend enums in C#/Java? I mean \"extend\" in both the sense of adding new values to an enum, but a

相关标签:
15条回答
  • 2020-11-27 18:30

    Some time back even i wanted to do something like this and found that enum extensions would voilate lot of basic concepts... (Not just polymorphisim)

    But still u might need to do if the enum is declared in external library and Remember you should make a special caution when using this enum extensions...

    public enum MyEnum { A = 1, B = 2, C = 4 }
    
    public const MyEnum D = (MyEnum)(8);
    public const MyEnum E = (MyEnum)(16);
    
    func1{
        MyEnum EnumValue = D;
    
        switch (EnumValue){
          case D:  break;
          case E:  break;
          case MyEnum.A:  break;
          case MyEnum.B:  break;
       }
    }
    
    0 讨论(0)
  • 2020-11-27 18:31

    The reason you can't extend Enums is because it would lead to problems with polymorphism.

    Say you have an enum MyEnum with values A, B, and C , and extend it with value D as MyExtEnum.

    Suppose a method expects a myEnum value somewhere, for instance as a parameter. It should be legal to supply a MyExtEnum value, because it's a subtype, but now what are you going to do when it turns out the value is D?

    To eliminate this problem, extending enums is illegal

    0 讨论(0)
  • 2020-11-27 18:34

    When built-in enums aren't enough, you can do it the old fashion way and craft your own. For example, if you wanted to add an additional property, for example, a description field, you could do it as follows:

    public class Action {
        public string Name {get; private set;}
        public string Description {get; private set;}
    
        private Action(string name, string description) {
            Name = name;
            Description = description;
        }
    
        public static Action DoIt = new Action("Do it", "This does things");
        public static Action StopIt = new Action("Stop It", "This stops things");
    }
    

    You can then treat it like an enum like so:

    public void ProcessAction(Action a) {
        Console.WriteLine("Performing action: " + a.Name)
        if (a == Action.DoIt) {
           // ... and so on
        }
    }
    

    The trick is to make sure that the constructor is private (or protected if you want to inherit), and that your instances are static.

    0 讨论(0)
提交回复
热议问题