将If语句转换为Switch

本文关键字:Switch 转换 语句 If | 更新日期: 2023-09-27 17:49:33

我有这个If语句,我想把它们移动到大小写切换

下面是我的if语句:

if (rResponse.ErrorCode[0] == 0x20 && rResponse.ErrorCode[1] == 0x03)
    ErrorMsg = "COMM_FRAME_ERROR";
if (rResponse.ErrorCode[0] == 0x20 && rResponse.ErrorCode[1] == 0x04)
    ErrorMsg = "JAM";
if (rResponse.ErrorCode[0] == 0x20 && rResponse.ErrorCode[1] == 0x05)
    ErrorMsg = "NO_CARD";

我该怎么做呢?

将If语句转换为Switch

if (rResponse.ErrorCode[0] == 0x20) {
  switch(rResponse.ErrorCode[1]) {
    case 0x03:
      ErrorMsg = "COMM_FRAME_ERROR";
      break;
    case 0x04:
      ErrorMsg = "JAM";
      break;
    case 0x05:
      ErrorMsg = "NO_CARD";
      break;
  }
}

如果您希望两者同时使用:

switch(rResponse.Errorcode[0])
case 0x20:
    switch(rResponse.ErrorCode[1]) {
        case 0x03:
            ErrorMsg = "COMM_FRAME_ERROR";
            break;
        case 0x04:
            ErrorMsg = "JAM";
            break;
        case 0x05:
            ErrorMsg = "NO_CARD";
            break;
    }
    break;

可以省略或更改异常,

if (rResponse.ErrorCode[0] == 0x20)
        {
            switch (rResponse.ErrorCode[1])
            {
                case 0x03:
                    ErrorMsg = "COMM_FRAME_ERROR";
                    break;
                case 0x04:
                    ErrorMsg = "JAM";
                    break;
                case 0x05:
                    ErrorMsg = "NO_CARD";
                    break;
                default:
                    throw new InvalidOperationException();
                    break;
            }
        }
switch(rResponse.Errorcode[0])
{
 case 0x20:
  switch(rResponse.ErrorCode[1]) 
  {
    case 0x03:
        ErrorMsg = "COMM_FRAME_ERROR";
        break;
    case 0x04:
        ErrorMsg = "JAM";
        break;
    case 0x05:
        ErrorMsg = "NO_CARD";
        break;
  }
  break;
}

你可以试试这样做…

 switch (rResponse.ErrorCode[0] + rResponse.ErrorCode[1])
       {
        case (0x20 + 0x03):
              ErrorMsg = "COMM_FRAME_ERROR";
              break;
       case (0x20 + 0x04):
              ....
      }

虽然这可能不适合所有的情况,

尽管根据提供的信息,意大利的反应可能是最好的。但如果这个误差部分在更大的范围内,那么下面的方法可能值得一试。(类似的方法,只是便于添加。

private string GetError(byte response1, byte response2)
{
    var ErrorMessage = "";
    switch (response1)
    {
        case 0x20:
            ErrorMessage = ParseCardErrors(response2);
            break;
        case 0x21:
            ErrorMessage = ParseDeviceErrors(response2);
            break;
        default:
            ErrorMessage = "Unknown Error";
    }
    return ErrorMessage;
}
private string ParseCardErrors(byte response)
{
  switch(response)
    {
        case 0x03:
          return "COMM_FRAME_ERROR";
        case 0x04:
          return "JAM";
        case 0x05:
          return "NO_CARD";
        default:
            return "Unknown card Error";
    }
}
private string ParseDeviceErrors(byte response)
{
  switch(response)
    {
        case 0x03:
          return "COMM_FRAME_ERROR";
        case 0x04:
          return "Unplugged";
        case 0x05:
          return "No device";
        default:
            return "Unknown device Error";
    }
}

我可能会发布一个非常不同的解决方案这个问题,但它可以回答@Robert问题:

class Program
{
    //This can be included in Seprate class also
    public enum ErrorMessages
    {
        //Store any Values as Key and Pair
        // Provide and easy way to update answers
        Error1 = 1,
        Error2 = 2,
        Error3 = 3,
        Error4 = 4
    }
    public static void Main()
    {
        ICollection<EnumValueDto> list = EnumValueDto.ConvertEnumToList<ErrorMessages>();
        foreach (var element in list)
        {
            Console.WriteLine(string.Format("Key: {0}; Value: {1}", element.Key, element.Value));
        }
        Console.Read();
        /* OUTPUT:
           Key: 1; Value: Error1
           Key: 2; Value: Error2
           Key: 3; Value: Error3 
           Key: 4; Value: Error4
        */
    }
    public class EnumValueDto
    {
        public int Key { get; set; }
        public string Value { get; set; }
        public static ICollection<EnumValueDto> ConvertEnumToList<T>() where T : struct, IConvertible
        {
            if (!typeof(T).IsEnum)
            {
                throw new Exception("Type given T must be an Enum");
            }
            var result = Enum.GetValues(typeof(T))
                             .Cast<T>()
                             .Select(x => new EnumValueDto
                             {
                                 Key = Convert.ToInt32(x),//values are arbitary here any datatype will work
                                 Value = x.ToString(new CultureInfo("en"))
                             })
                            .Where(err => err.Key==3) //Instead of 3 as key here use Response variable instead
                            .ToList()
                            .AsReadOnly();
            return result;
        }
    }

}