简体   繁体   English

如何在C#中使用字节常量作为切换条件?

[英]How do I use byte constants as switch cases in C#?

I'm developing a network protocol that needs to be as low-bandwidth as possible. 我正在开发一种网络协议,该协议需要尽可能低的带宽。 I've decided therefore that instead of using a header that is a string for each message type, such as "connect" , "move" or "disconnect" , it would be better to use a byte . 因此,我已经决定,与其使用对于每种消息类型都是string的标头,例如"connect""move""disconnect" ,最好使用byte

Here's a snippet of what I have so far: 这是我到目前为止的摘要:

// Message types
public static readonly byte CONNECT = 100;
public static readonly byte MOVE = 101;
public static readonly byte DISCONNECT = 102;

Now elsewhere I have: 现在我在其他地方:

switch (in_message.ReadByte())
{
    case CONNECT: Connect(); break;
    case MOVE: Move(); break;
    case DISCONNECT: Disconnect(); break;
}
Client.Recycle(in_message);

Visual Studio doesn't seem to like the fact that I'm using byte constants, the specific error message is A constant value is expected . Visual Studio似乎不喜欢我使用字节常量的事实,特定的错误消息A constant value is expected

Is there any way I can get these byte constants to work with the switch statement? 有什么办法可以使这些字节常量与switch语句一起使用?

What you have are read-only fields, which aren't considered constant values (they can be assigned to by a static constructor). 您拥有的是只读字段,这些字段不被视为常量值(可以由静态构造函数分配给它们)。 Use constants instead: 使用常量代替:

public const byte CONNECT = 100;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM