将很多 if 转换为更小的内容
本文关键字:if 转换 | 更新日期: 2023-09-27 17:55:37
我需要检查一个字符数组并将每个字符转换为随机数值转换为 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;
}
这只是一个示例,因为我需要检查每个数字和字母类型。谢谢!
我认为最简单的
方法是使用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]];
}
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.
}
}
}
怎么样:
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
}