c# - 如果检查反转

标签 c# if-statement

我有一个巨大的检查列表,例如检查整数是 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/

相关文章:

c# - Windows 10 上的 .NET FontFamily 内存泄漏

c# - ASP.Net Controller Action 仅在任务完成后返回

c# - 需要有关提高 C# 代码性能的建议

vb.net - 多个 if 语句检查字符串长度并缩短

c++ - 编译器错误 `assigning incompatible type within if statement`

java - 使用数组初始化语法有条件地添加 "optional items"?

c# - LINQ 查询以识别系列中的片段

c# - 有没有办法在 Json.Net JsonSerializer 中使用自定义缩进字符?

if-statement - 避免在 IF 中重复相同的参数

loops - 在 ARM 汇编中创建嵌套 If 语句