c# - 多个场景的if语句

标签 c#

我正在努力完成这个 if 语句。必须有一种更简单的方法来完成所有组合,因为这不是好的做法。

if( one == true && two == true && three == true ...)
else if( one != true && two == true && three == true ...)

我想知道我是否想遍历所有组合是否有任何其他方法可以做到这一点而不是复制表达式?

最佳答案

一种方法是将您的 onetwothree 值转换为单个 int正确设置位,并在二进制掩码上使用 switch 语句,如下所示:

int combined=0;
// Construct a binary representation using your Boolean values as bits:
// Value of one goes to bit zero
if (one) combined   |= (1 << 0);
// Value of one goes to bit one
if (two) combined   |= (1 << 1);
// Value of three goes to bit two
if (three) combined |= (1 << 2);
switch (combined) {
case 0: // All false
    break;
case 1: // one is true, other are all false
    break;
...
case 7: // All true
    break;
}

所有八个组合现在都编码为整数值:

int    three two one
_--    ----- --- ---
0    -    0   0   0 
1    -    0   0   1 
2    -    0   1   0 
3    -    0   1   1 
4    -    1   0   0 
5    -    1   0   1 
6    -    1   1   0 
7    -    1   1   1 

不用说,对于没有记住小数的二进制表示的代码读者,您需要对这样的代码进行大量注释。

关于c# - 多个场景的if语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26347287/

相关文章:

C#:四舍五入小数,只在小数点为0时才显示(eg: 3.00 --> 3)

c# - 这个属性是什么?

c# - 高效的位重映射算法

c# - 将动态参数传递给类似的函数

c# - 使用 Entity Framework 创建临时表

c# - 选择数据库结构/引擎的指南

c# - 创建通用检索方法以返回 1 条记录

c# - 从 C 到 C# 的错误编码

c# - ASP.Net MVC5、Google OAuth 2.0 和 Youtube API

c# - 如何在用户每次完成笔划时进行手写识别?