Enum “Inheritance”

后端 未结 15 1502
野性不改
野性不改 2020-11-22 07:21

I have an enum in a low level namespace. I\'d like to provide a class or enum in a mid level namespace that \"inherits\" the low level enum.

namespace low
{
         


        
15条回答
  •  一生所求
    2020-11-22 08:11

    The solutions above using classes with int constants lack type-safety. I.e. you could invent new values actually not defined in the class. Furthermore it is not possible for example to write a method taking one of these classes as input.

    You would need to write

    public void DoSomethingMeaningFull(int consumeValue) ...
    

    However, there is a class based solution of the old days of Java, when there were no enums available. This provides an almost enum-like behaviour. The only caveat is that these constants cannot be used within a switch-statement.

    public class MyBaseEnum
    {
        public static readonly MyBaseEnum A = new MyBaseEnum( 1 );
        public static readonly MyBaseEnum B = new MyBaseEnum( 2 );
        public static readonly MyBaseEnum C = new MyBaseEnum( 3 );
    
        public int InternalValue { get; protected set; }
    
        protected MyBaseEnum( int internalValue )
        {
            this.InternalValue = internalValue;
        }
    }
    
    public class MyEnum : MyBaseEnum
    {
        public static readonly MyEnum D = new MyEnum( 4 );
        public static readonly MyEnum E = new MyEnum( 5 );
    
        protected MyEnum( int internalValue ) : base( internalValue )
        {
            // Nothing
        }
    }
    
    [TestMethod]
    public void EnumTest()
    {
        this.DoSomethingMeaningful( MyEnum.A );
    }
    
    private void DoSomethingMeaningful( MyBaseEnum enumValue )
    {
        // ...
        if( enumValue == MyEnum.A ) { /* ... */ }
        else if (enumValue == MyEnum.B) { /* ... */ }
        // ...
    }
    

提交回复
热议问题