根据枚举检查值 [英] Checking the value against enumeration

查看:85
本文介绍了根据枚举检查值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的枚举:

I have enumeration like this:

 public enum returnCodes
        {

            Success = 0,
            Timeout = 1,
            GeneralReject = 0x10,
            ServiceNotSupported = 0x11,
            SubFunctionNotSupported = 0x12,
            InvalidMessageLength = 0x13,
            BusyRepeatRequest = 0x21
}



我得到的结果是字节数组.我想检查枚举中是否有第三个字节.如果是,则显示一些消息.
为此,我可以像这样单独检查每个值:



I have a result that is byte array. I want to check if 3rd byte out there is among any of the values in enumeration. If yes then display some message.
For that i can individually check each value like this:

if (_receivedFrame.Data[2] == (int)returnCodes.GeneralReject)
           {
               MessageBox.Show("first");
           }
           else if (_receivedFrame.Data[2] == (int)returnCodes.Success)
           {
               MessageBox.Show("second");
           }



但是我想知道是否有任何有效的编码方式,可以将3rd字节与enumaration中的所有值进行比较.



But i want to know if there is any efficent way of coding where i can compare 3rd byte with all values in enumaration.

推荐答案

为此我写了一个提示/技巧:

从有问题的数据源(对于C#和VB)设置枚举器 [ ^ ]

您可以通过以下方式使用它:

I wrote a tip/trick for this:

Setting Enumerators From Questionable Data Sources (for C# and VB)[^]

You would use it this way:

if (IntToEnum(_receivedFrame.Data[2], returnCodes.GeneralReject) == returnCodes.Success)
{
    // do something

}


您可以使用Enum.GetValues:
You could use Enum.GetValues :
var enumValues = Enum.GetValues(typeof(returnCodes));
foreach (object enumValue in enumValues)
{
   if((returnCodes)enumValue == _receivedFrame.Data[2])
   {
       //Do something
   }
}



或者,您可以在静态构造函数中加载Dictionary ,然后查找要返回的字符串.



Alternately, you could load a Dictionary in the static constructor and just look up the string to return.


这篇关于根据枚举检查值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆