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

后端 未结 7 419
谎友^
谎友^ 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:29

    1. Create an Enum for LoginResponse, SelectionResponse, etc., but don't specify the values.

    2. Have ServerOperationCode and ClientOperationCode implement a function that, given an integer bytecode, returns the appropriate value from your Enum.

    Example:

    public enum OperationCode
    {
     LoginResponse,
     SelectionResponse,
     BlahBlahResponse
    }
    
    public interface IOperationCodeTranslator {
     public OperationCode GetOperationCode(byte inputcode);
     }
    
    public class ServerOperationCode : IOperationCodeTranslator
    {
      public OperationCode GetOperationCode(byte inputcode) {
        switch(inputcode) {
           case 0x00: return OperationCode.LoginResponse;
          [...]
        } 
    }
    

    Caveat: since interfaces can't define static functions, ServerOperationCode and ClientOperationCode would only be able to implement a common interface if said function is an instance function. If they don't need to implement a common interface, GetOperationCode can be a static function.

    (Apologies for any C# snafus, it's not my first language...)

提交回复
热议问题