枚举中的值范围有多个线程(不可能).但我有以下问题并搜索最佳解决方案,其中没有一个提供曾经真的让我满意.
协议规范说消息的byte [x],messagetype,具有以下可能的值(幻想值):
0x00 = get
0x01 = set
0x02 to 0xFF = identify
Run Code Online (Sandbox Code Playgroud)
因此,只有3种不同的逻辑选项,最好在枚举中处理.但是,n个逻辑选项中的一个具有m个不同的数字对应物,这在枚举中是不可能处理的.
现在这个问题的最佳(最干净)解决方案是什么?我可以建立一个班级
class MessageType {
public enum MessageTypeEnum {
get = 0x00,
set = 0x01,
identify = 0x02
}
public static MessageTypeEnum getLogicalValue (byte numericalValue)
{
if (numericalValue < 0x02)
return (MessageTypeEnum(numericalValue));
else
return MessageTypeEnum.identify;
}
}
Run Code Online (Sandbox Code Playgroud)
我也可以创建一个没有枚举的类,但是使用静态成员.
无论哪种方式都存在一个问题:如果有人试图发送数据包,他可能会使用
if (messageBytes[x] == (byte)MessageTypeEnum.identify) {
// do stuff
}
Run Code Online (Sandbox Code Playgroud)
但是messageByte [x]可以是0x02和0xFF之间的任何值,因此"点击"枚举中指定的值将是纯粹的运气.另一方面,我希望将enum(或静态成员)公开以便于构建消息.
我可以以某种方式强制使用我的getLogicalValue() - 函数?有更优雅的解决方案吗?
我想要的是一种简单且结构良好的方法,可以将逻辑值链接到:m关系中的数值.特别是因为给定的协议有很多这样的情况,我想保持我的代码整洁.
谢谢你的帮助和时间:)
贾尼斯
我建议您放弃使用枚举的想法并为此创建一个自定义类型。
它可以是结构体或类;没关系。==您可以通过重载运算符并提供自定义实现来解决等于问题。
像这样的东西:
public class MessageType
{
private readonly byte value;
private MessageType(byte value)
{
this.value = value;
}
public static readonly MessageType Get = new MessageType(0);
public static readonly MessageType Set = new MessageType(1);
public static readonly MessageType Identify = new MessageType(2);
public static bool operator ==(MessageType m, byte b)
{
if (object.ReferenceEquals(m, null))
return false;
if (m.value == 2 && b >= 2 && b <= 0xff)//I think <= check is redundant
return true;
return m.value == b;
}
public static bool operator !=(MessageType m, byte b)
{
return !(m == b);
}
//Need to implement Equals, GetHashCode etc
}
Run Code Online (Sandbox Code Playgroud)
不要忘记实现equals 实现的一致性Equals。GetHashCode