我怎样才能制作一个“抽象"?.NET 类库中的枚举? [英] How can I make an "abstract" enum in a .NET class library?
问题描述
我正在制作一个服务器库,其中的数据包关联是通过枚举完成的.
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
}
当您在自己的项目中工作时,这很好用 - 您可以比较返回的枚举成员(即 if (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
返回一个字节,您可能必须为字节实现 == 运算符.将此代码放入您的抽象 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 类库中的枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!