将许多if转换为更小的东西

时间:2016-07-06 19:37:43

标签: c#

我需要检查一个char数组并将每个char转换为一个随机数值为int数组;

我已经设法做了这个但是有很多代码。 无论如何我可以写更少的代码吗?

for (int i = 0; i < 8; i++)
        {
            if (oddF[i] == '0')
            {
                oddFlValue[i] = 1;
                continue;
            }
            else if (oddF[i] == '1')
            {
                oddFValue[i] = 0;
                continue;
            }
            else if (oddFiscal[i] == '8')
            {
                oddFiscalValue[i] = 19;
                continue;
            }
            else if (oddF[i] == '9')
            {
                oddFValue[i] = 21;
                continue;
            }
            else if ((oddF[i] == 'a') || (oddF[i] == 'A'))
            {
                oddFValue[i] = 1;
                continue;
            }
            else if ((oddF[i] == 'b') || (oddF[i] == 'B'))
            {
                oddFValue[i] = 0;
                continue;
            }

这只是一个示例,因为我需要检查每个数字和字母类型。 谢谢!

3 个答案:

答案 0 :(得分:1)

我认为最简单的方法是使用Dictionary<char, int>,并获得其价值。像这样:

Dictionary<char, int> MyCombinations = new Dictionary<char, int>{
    {'0', 1},
    {'5', 15},
    /*etc etc etc*/
}; 

然后使用它:

for (int i = 0; i < 8; i++)
{
    oddFValue[i] = MyCombinations[oddFiscal[i]];
}

答案 1 :(得分:0)

class Program
{
    static void Main(string[] args)
    {
        char[] oddF           = new char[8]{'0','1','8','A','b','9','a','B'};
         int[] oddFValue      = new int[8];

        Dictionary<char, int> table = new Dictionary<char, int>(){
            { '0', 1  },
            { '1', 0  },
            { '8', 19 },
            { '9', 21 },
            { 'a', 1  },
            { 'A', 1  },
            { 'b', 0  },
            { 'B', 0  }
        };

        for (int i = 0; i < 8; i++)
        {
            oddFValue[i] = table[oddF[i]]; // Lookup which function should be called, and call it.
        }
    }
}

答案 2 :(得分:-1)

怎么样:

public int? ConvertCharToInt(char c)
{
    switch (c)
    {
        case '0': return 1;
        case '1': return 0;
        case '8': return 19;
        case '9': return 21;
        case 'a':
        case 'A': return 1;
        case 'b':
        case 'B': return 0;
        // ...
        default: return null;
    }
}

然后:

for (int i = 0; i < 8; i++)
{
    int? number = ConvertCharToInt(oddF[i]);
    if (number.HasValue)
         oddFValue[i] = number.Value;
    else
         // Character cannot be converted to int value
}