You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中if语句交换逻辑优化:如何避免重复编写或运算代码?

C#中实现“反之亦然”条件判断的优化写法

针对你需要判断currentDirection和nextDirection为1和2的任意组合的场景,这里有几种比重复写||更简洁的实现方式:

1. 使用C#元组模式(推荐,C# 7.0+)

这种写法最直观,语法简洁易读:

if ((currentDirection, nextDirection) is (1, 2) or (2, 1))
{
    // 你的逻辑代码
}

2. 封装辅助方法(适合多处复用场景)

如果这种“两两配对”的判断在代码中多次出现,封装成通用方法能提升复用性:

// 定义辅助方法
private bool IsPair(int first, int second, int targetA, int targetB)
{
    return (first == targetA && second == targetB) || (first == targetB && second == targetA);
}

// 调用示例
if (IsPair(currentDirection, nextDirection, 1, 2))
{
    // 你的逻辑代码
}

3. 利用数值运算(仅适用于固定的两个不同数值)

如果确定只需要判断1和2的组合,可以通过加法和乘法的特性来判断,不过这种方法局限性较强,仅适合特定数值场景:

if (currentDirection + nextDirection == 3 && currentDirection * nextDirection == 2)
{
    // 你的逻辑代码
}

原理是1+2=3,1×2=2,只有这两个数的组合能同时满足这两个等式。

4. 使用HashSet(通用型,支持更多数值组合)

如果需要判断的是两个值属于某一组固定值(比如不止两个值的场景),可以用HashSet的集合相等判断:

var directionSet = new HashSet<int> { currentDirection, nextDirection };
if (directionSet.SetEquals(new[] { 1, 2 }))
{
    // 你的逻辑代码
}

这种方法扩展性好,比如后续要判断1、2、3中的任意两个组合,只需要修改集合内的元素即可。

内容的提问来源于stack exchange,提问作者Cameron Lindo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 03:42:16