问题描述
我做在数据包关联是通过枚举做了服务器库
I'm making a server library in which the packet association is done by enum.
public enum ServerOperationCode : byte
{
LoginResponse = 0x00,
SelectionResponse = 0x01,
BlahBlahResponse = 0x02
}
public enum ClientOperationCode : byte
{
LoginRequest = 0x00,
SelectionRequest = 0x01,
BlahBlahRequest = 0x02
}
当你沉浸在自己的项目正在努力工作得很好 - 你可以比较返回该枚举成员(即如果(packet.OperationCode == ClientOperationCode.LoginRequest)
)。然而,由于这是一个类库,用户必须定义自己的枚举
That works fine when you're working in your own project - you can compare which enum member is returned (i.e. if (packet.OperationCode == ClientOperationCode.LoginRequest)
). However, since this is a class library, the user will have to define its own enum.
所以,我有两个枚举添加为抽象 - ServerOperationCode和ClientOperationCode 。我知道这是不可能实现在C#中抽象的枚举。我怎么会去这样做呢?
Therefore, I have two enums to add as "abstract" - ServerOperationCode and ClientOperationCode. I know it's not possible to implement abstract enums in C#. How would I go doing this?
推荐答案
我喜欢用静态实例上我的课,当我需要做到这一点。它可以让你有一些默认值也让它通过继承和接口实现的惯用手段是可扩展的:
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) { }
}
假设 packet.OperationCode
返回一个字节,你可能将不得不实施字节的==操作符。把这段代码到你的抽象类操作代码
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)
这篇关于我怎样才能让一个"抽象的"枚举在.NET类库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!