需要基于数组中 16 种不同 bool 模式之一在 C# (.NET 4.6.1) 中进行分支(为了提高此消息的可读性,0==false 和 1==true):
0000
0010
0100
0110
0001
0011
0101
0111
1000
1010
1100
1110
1001
1011
1101
1111
目前不关心整体性能,有什么好方法可以使这 16 种情况中的每一种情况的分支都易于人类阅读?其中一些中间有“00”的应该表现相同,而另一些则不然。
一个想法是将每个模式转换为字符串,然后执行 Switch 或 16 个“if”语句,这不太好。每个模式都是 BitArray 的重要部分,被提取并转换为 bool 数组。
最佳答案
(一种方法)将四个 bool 值转换为一个字节:
public byte BoolsToByte(IEnumerable<bool> bools)
{
byte result = 0;
foreach ( bool value in bools )
{
result *= 2;
if ( value )
result += 1;
}
return result;
}
public byte BoolsToByte(params bool[] bools)
{
return BoolsToByte(bools.AsEnumerable());
}
其中重载使您能够灵活地通过以下两种方式之一进行调用:
字节转换 = BoolsToByte(bytes);
字节转换 = BoolsToByte(a, b, c, d);
我无法让二进制文字工作(使用 Visual Studio 2015,针对 .NET 4.6.1)。其他 C# 6.0 功能,如 nameof
不过,工作。现在我将恢复到 5.0 行为并将二进制保留为注释。
如果您要编译到 .NET 4.6.1,我假设您正在使用 C# 6.0 功能,例如 binary literals这将有助于提高可读性。在这种情况下,您可以对 switch
语句的情况使用如下语法:
switch ( converted )
{
case 0: // 0000
// elided
break;
case 1: // 0001
case 9: // 1001
// elided
break;
// other cases elided
case 15: // 1111
// elided
break;
}
注意,我将 1 (0001
) 和 9 (1001
) 组合起来作为示例,因为您说:
Some of those that have "00" in the middle should behave the same, others not.
如果您不使用 C# 6.0 功能,只需将二进制文字替换为注释中的等效数字即可。
关于c# - C# 中基于 bool 模式的分支?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35206568/