基于布尔模式的 C# 分支?
Branch in C# Based on Boolean Pattern?
需要根据数组中 16 种不同布尔模式之一在 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 数组。
(一种方式)将您的四个布尔值转换为一个字节:
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());
}
重载使您可以灵活地以两种方式之一进行调用:
byte converted = BoolsToByte(bytes);
byte converted = BoolsToByte(a, b, c, d);
我无法使二进制文字正常工作(使用 Visual Studio 2015,针对 .NET 4.6.1)。不过, 等其他 C# 6.0 功能也可以使用。现在我恢复到 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 功能,只需将二进制文本替换为注释中的等效数字。
需要根据数组中 16 种不同布尔模式之一在 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 数组。
(一种方式)将您的四个布尔值转换为一个字节:
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());
}
重载使您可以灵活地以两种方式之一进行调用:
byte converted = BoolsToByte(bytes);
byte converted = BoolsToByte(a, b, c, d);
我无法使二进制文字正常工作(使用 Visual Studio 2015,针对 .NET 4.6.1)。不过,
如果您要编译为 .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 功能,只需将二进制文本替换为注释中的等效数字。