Enum “Inheritance”

后端 未结 15 1629
野性不改
野性不改 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:12

    You can achieve what you want with classes:

    public class Base
    {
        public const int A = 1;
        public const int B = 2;
        public const int C = 3;
    }
    public class Consume : Base
    {
        public const int D = 4;
        public const int E = 5;
    }
    

    Now you can use these classes similar as when they were enums:

    int i = Consume.B;
    

    Update (after your update of the question):

    If you assign the same int values to the constants as defined in the existing enum, then you can cast between the enum and the constants, e.g:

    public enum SomeEnum // this is the existing enum (from WSDL)
    {
        A = 1,
        B = 2,
        ...
    }
    public class Base
    {
        public const int A = (int)SomeEnum.A;
        //...
    }
    public class Consume : Base
    {
        public const int D = 4;
        public const int E = 5;
    }
    
    // where you have to use the enum, use a cast:
    SomeEnum e = (SomeEnum)Consume.B;
    

提交回复
热议问题