我有一个巨大的检查列表,例如检查整数是 4 还是 10,如果它是 4,它会将这个 int 更改为 10,反之亦然,所以我的 if 检查将是这样的:
int i = getval();
if (i == 4)
{
i = 10;
}
else if (i == 10)
{
i = 4;
}
我的问题是还有另一种方法可以做到这一点而无需检查每个条件。
最佳答案
如果你有一个巨大的列表,你可能会考虑一些列表结构。
static Dictionary<int, int> exchange = new Dictionary<int, int>();
static Constructor()
{
AddExchangePair(4, 10);
AddExchangePair(3, 12);
...
}
static void AddExchangePair(int a, int b)
{
exchange.Add(a,b);
exchange.Add(b,a);
}
public staic bool Exchange(ref int value)
{
int newValue = 0;
bool exchanged = exchange.TryGetValue(value, out newValue);
if (exchanged) value = newValue;
return exchanged;
}
这适用于庞大的交易对列表。
如果您使用重复的号码调用 AddExchangePair,例如(7,14) 和 (14, 16) 你会得到一个异常(exception)。您可能需要考虑在这种情况下该怎么做。
关于c# - 如果检查反转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13091535/