将If语句转换为Switch

时间:2012-12-27 04:46:58

标签: c# if-statement switch-statement

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

这是我的,如果Stataments:

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

我该怎么做?

7 个答案:

答案 0 :(得分:9)

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

答案 1 :(得分:1)

如果你想在两种情况下都需要:

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;

答案 2 :(得分: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;
                default:
                    throw new InvalidOperationException();
                    break;
            }
        }

答案 3 :(得分:0)

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

答案 4 :(得分:0)

你可以尝试这样的事情......

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

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

答案 5 :(得分:0)

尽管提供的信息,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";
    }
}

答案 6 :(得分:0)

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


}