我正在创建一个服务器库,其中数据包关联由枚举完成.
public enum ServerOperationCode : byte { LoginResponse = 0x00,SelectionResponse = 0x01,BlahBlahResponse = 0x02 } public enum ClientOperationCode : byte { LoginRequest = 0x00,SelectionRequest = 0x01,BlahBlahRequest = 0x02 }
当您在自己的项目中工作时,可以正常工作 – 您可以比较返回哪个枚举成员(即if(packet.OperationCode == ClientOperationCode.LoginRequest)).但是,由于这是一个类库,所以用户必须定义自己的枚举.
因此,我有两个枚举添加为“抽象” – ServerOperationCode和ClientOperationCode.我知道不可能在C#中实现抽象枚举.我该怎么办?
解决方法
当我需要这样做时,我喜欢在我的类上使用静态实例.它允许您具有一些默认值,但也可以通过继承和接口实现的通常手段进行扩展:
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) { } }
假设packet.OperationCode返回一个字节,你可能必须为字节实现一个==运算符.将此代码放入您的抽象OperationCode类中.
public static bool operator ==(OperationCode a,OperationCode b) { return a.Code == b.Code; } public static bool operator !=(OperationCode a,OperationCode b) { return !(a == b); }
这将允许您与您所显示的相同的支票:
if (packet.OperationCode == ClientOperationCode.LoginRequest)