How can I make an “abstract” enum in a .NET class library?

后端 未结 7 417
谎友^
谎友^ 2020-12-29 10:17

I\'m making a server library in which the packet association is done by enum.

public enum ServerOperationCode : byte
{
    LoginResponse = 0x00,
    Selectio         


        
7条回答
  •  孤独总比滥情好
    2020-12-29 10:43

    I like to use static instances on my classes when I need to do this. It allows you to have some default values but also lets it be extensible through the usual means of inheritance and interface implementations:

        public abstract class OperationCode
        {
            public byte Code { get; private set; }
            public OperationCode(byte code)
            {
                Code = code;
            }
        }
    
        public class ServerOperationCode : OperationCode
        {
            public static ServerOperationCode LoginResponse = new ServerOperationCode(0x00);
            public static ServerOperationCode SelectionResponse = new ServerOperationCode(0x01);
            public static ServerOperationCode BlahBlahResponse = new ServerOperationCode(0x02);
    
            public ServerOperationCode(byte code) : base(code) { }
        }
    
        public class ClientOperationCode : OperationCode
        {
            public static ClientOperationCode LoginRequest = new ClientOperationCode(0x00);
            public static ClientOperationCode SelectionRequest = new ClientOperationCode(0x01);
            public static ClientOperationCode BlahBlahRequest = new ClientOperationCode(0x02);
    
            public ClientOperationCode(byte code) : base(code) { }
        }
    

    assuming packet.OperationCode return a byte, you will likely have to implement an == operator for byte. put this code into your abstract OperationCode class.

    public static bool operator ==(OperationCode a, OperationCode b)
    {
      return a.Code == b.Code;
    }
    
    public static bool operator !=(OperationCode a, OperationCode b)
    {
      return !(a == b);
    }
    

    this will allow you to have the same check as you showed:

    if (packet.OperationCode == ClientOperationCode.LoginRequest)

提交回复
热议问题