【问题标题】:Convert If Statement into Switch将 If 语句转换为 Switch
【发布时间】:2012-12-27 04:46:57
【问题描述】:

我有这个 If 语句,我想将它们移到 Case-Switch 中

这是我的 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";

我该怎么做?

【问题讨论】:

  • 我认为 Itay 更好地解释了您也可以使用嵌套开关的方式。
  • @Pratik 根据我的经验,最好不要下一个开关。它会使阅读变得非常困难。由于这看起来像是来自程序的错误处理部分,我认为最好按照 Itay 所说的去做,或者为两个字节制作一个“解析器”,我会发布我的想法作为答案。
  • @RobertSnyder 完全同意。我总是避免使用 switch 语句,我最好使用Database or any generic function(list or any entity)
  • 现在这是我不知道的事情。我将不得不对此进行调查,因为我刚刚完成了与 OP 在我的项目中所做的类似的事情。我的反应类似于我解决它的方法。您能否详细说明您的想法?
  • @RobertSnyder 我已经发表了我的想法。这不是解决这些小问题所需要的,而是创建Entities 之类的可扩展的枚举。

标签: c# if-statement switch-statement


【解决方案1】:
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;
  }
}

【讨论】:

    【解决方案2】:

    如果你想要两个都在 switch 案例中:

    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;
    

    【讨论】:

      【解决方案3】:

      可以省略或更改异常,

      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;
                  }
              }
      

      【讨论】:

        【解决方案4】:
        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;
        }
        

        【讨论】:

        • 先生。阿南德,你不认为我们的答案是一样的吗?
        【解决方案5】:

        你可以试试这样的..

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

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

        【讨论】:

          【解决方案6】:

          尽管 Itay 提供的信息可能是最好的。但是,如果这个错误部分的规模更大,那么下面的内容可能值得一试。 (类似的方法,只是更容易添加。

          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";
              }
          }
          

          【讨论】:

            【解决方案7】:

            我可能会发布一个非常不同的解决方案这个问题,但它可以回答@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;
                    }
                }
            
            
            }
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2023-04-08
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多