在 C# 中处理 If 语句的排列
Handling Permutations of If Statements in C#
我有一些存储值的列表。现在我想创建 If 语句来处理这个问题,但仅此而已。例如:
if(list1.Count==0 && list2.Count==0)
{
//do something
}
if(list1.Count==0 && list3.Count==0)
{
//do something
}
if(list1.Count==0 && list2.Count==0 && list3.Count==0)
{
//do something
}
所以如果我有大约 10 个列表,就会有大量的 if 语句。有更好的方法来处理吗?我还没有发现任何有用的东西。
谢谢!
看到粘贴在这里的代码,我可以给出建议的一种方式是你有一些像这样的重复内容
if(list1.Count==0 && list2.Count==0)
然后
if(list1.Count==0 && list2.Count==0 && list3.Count==0)
其中一个建议是像这样预先计算条件
bool onetwo = list1.Count==0 && list2.Count==0;
bool thirdalone = list3.Count == 0;
现在代码可以像这样更好
if(onetwo){
}
if(onetwo && thirdalone){
}
例如,如果您希望可以使用位掩码生成所有列表,这里的 n 是我们拥有的列表总数。
bool[] statu = new bool[1 << n];
for(int i = 1 ; i < (1<< n) ; i++){
bool result = true;
for(int j = 0 ; j < 32 ; j++){
if(i & ( 1 << j) > 0){
//this position is part of set
if(list[j].count == 0)
result = false;
}
}
status[i] = result;
}
但这只是更语义化的方式,不能提高性能等。
如果您需要检查每个排列,您可以这样做:
bool b1 = ( list1.count == 0 );
bool b2 = ( list2.count == 0 );
bool b3 = ( list3.count == 0 );
bool b4 = ( list4.count == 0 );
// etc etc
BitArray arr = new BitArray(new bool[4] { b1, b2, b3, b4 });
byte[] bits = new byte[4];
arr.CopyTo(bits, 0);
int x = BitConverter.ToInt32(bits, 0);
switch (x)
{
case 1: // only list 1 is empty
case 2: // only list 2 is empty
case 3: // only list 1 and list 2 are empty
case x: // and so on.
}
我不会说它是否更具可读性,但我宁愿维护这样的未来而不是巨大的 if/else/else if 块。
我有一些存储值的列表。现在我想创建 If 语句来处理这个问题,但仅此而已。例如:
if(list1.Count==0 && list2.Count==0)
{
//do something
}
if(list1.Count==0 && list3.Count==0)
{
//do something
}
if(list1.Count==0 && list2.Count==0 && list3.Count==0)
{
//do something
}
所以如果我有大约 10 个列表,就会有大量的 if 语句。有更好的方法来处理吗?我还没有发现任何有用的东西。 谢谢!
看到粘贴在这里的代码,我可以给出建议的一种方式是你有一些像这样的重复内容
if(list1.Count==0 && list2.Count==0)
然后
if(list1.Count==0 && list2.Count==0 && list3.Count==0)
其中一个建议是像这样预先计算条件
bool onetwo = list1.Count==0 && list2.Count==0;
bool thirdalone = list3.Count == 0;
现在代码可以像这样更好
if(onetwo){
}
if(onetwo && thirdalone){
}
例如,如果您希望可以使用位掩码生成所有列表,这里的 n 是我们拥有的列表总数。
bool[] statu = new bool[1 << n];
for(int i = 1 ; i < (1<< n) ; i++){
bool result = true;
for(int j = 0 ; j < 32 ; j++){
if(i & ( 1 << j) > 0){
//this position is part of set
if(list[j].count == 0)
result = false;
}
}
status[i] = result;
}
但这只是更语义化的方式,不能提高性能等。
如果您需要检查每个排列,您可以这样做:
bool b1 = ( list1.count == 0 );
bool b2 = ( list2.count == 0 );
bool b3 = ( list3.count == 0 );
bool b4 = ( list4.count == 0 );
// etc etc
BitArray arr = new BitArray(new bool[4] { b1, b2, b3, b4 });
byte[] bits = new byte[4];
arr.CopyTo(bits, 0);
int x = BitConverter.ToInt32(bits, 0);
switch (x)
{
case 1: // only list 1 is empty
case 2: // only list 2 is empty
case 3: // only list 1 and list 2 are empty
case x: // and so on.
}
我不会说它是否更具可读性,但我宁愿维护这样的未来而不是巨大的 if/else/else if 块。