how can i use switch statement on type-safe enum pattern

后端 未结 3 1182
被撕碎了的回忆
被撕碎了的回忆 2021-02-05 09:51

I found a goodlooking example about implementation enums in a different way. That is called type-safe enum pattern i think. I started using it but i realized th

3条回答
  •  春和景丽
    2021-02-05 10:02

    The type-safe enum pattern is interesting because you can add behavior to individual enum members (which are instances). So, if the behavior you want to switch-on could be part of the class, just use polymorphism. Note that you might need to create subclasses for each member that overrides the behavior:

    public class MyState {
    
      public static readonly MyState Passed = new MyStatePassed();
      public static readonly MyState Failed = new MyStateFailed();
    
      public virtual void SomeLogic() {
        // default logic, or make it abstract
      }
    
      class MyStatePassed : MyState {
        public MyStatePassed() : base(1, "OK") { }
      }
      class MyStateFailed : MyState {
        public MyStateFailed() : base(2, "Error") { }
        public override void SomeLogic() { 
          // Error specific logic!
        }
      }
    
      ...
    }
    

    Usage:

    MyState state = ...
    state.someLogic();
    

    Now, if the logic clearly doesn't belong and you really want to switch, my advice is to create a sibling enum:

    public enum MyStateValue { 
      Passed = 1, Failed = 2
    }
    public sealed class MyState {
      public static readonly MyState Passed = new MyState(MyStateValue.Passed, "OK");
      public static readonly MyState Failed = new MyState(MyStateValue.Failed, "Error");
    
      public MyStateValue Value { get; private set; }
    
      private MyState(MyStateValue value, string name) {
        ...
      }
    }
    

    And switch on that:

    switch (state.Value) {
      case MyStateValue.Passed: ...
      case MyStateValue.Failed: ...
    }
    

    In this case, if the type-safe enum class doesn't have any behavior, there's not much reason for it to exist in place of the enum itself. But of course, you can have logic and a sibling enum at the same time.

提交回复
热议问题