加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如果检查则反转

发布时间:2020-12-15 19:46:07 所属栏目:百科 来源:网络整理
导读:我有一个巨大的检查列表,检查例如,如果整数是4或10,如果它是4,它将此int更改为10,反之亦然,所以我的检查将是这样的: int i = getval();if (i == 4){ i = 10;}else if (i == 10){ i = 4;} 我的问题是有另一种方法可以做到这一点,而无需检查每个条件. 解决方
我有一个巨大的检查列表,检查例如,如果整数是4或10,如果它是4,它将此int更改为10,反之亦然,所以我的检查将是这样的:

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)你会得到一个例外.您可能必须考虑在这种情况下该怎么做.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读