我有一个方法可以执行如下所示的操作:
// check if bits 6,7,8 are zero
if ((num >> 5) != 0)
{
//do some thing
return false;
}
// check if bits 2 ,3,4 are zero
if ((num & 0x0E) != 0)
{
//do something
return false;
}
// check if bit 1 is 1
if ((num & 1) != 1)
{
//dosomething
return false;
}
Run Code Online (Sandbox Code Playgroud)
现在我想添加扩展方法,如:
num
.arebitsset((6,7,8) ,(do some action and return from method if false , if true allow chaining))
.arebitsset(2,3,4) , <same as above>)
.......
Run Code Online (Sandbox Code Playgroud)
虽然我知道 bitset 检查的逻辑,但我需要知道如何从方法返回或允许基于真/假结果的链接。
可以使用func吗?我不确定。
注意:我有 80 个这样的条件要在下面进行测试,所以写 80 个 if 条件是否好,当然不是,所以我需要一些紧凑的形式
你可以写这样的扩展方法:
public static class BitSetExtensions
{
private static bool AreBitsSet(int i, int[] bits)
{
// you already have this
}
public static (int value, bool valid) CallActionIfBitsSet(this int value, int[] bits, Action action)
{
return CallActionIfBitsSet((value, true), bits, action);
}
public static (int value, bool valid) CallActionIfBitsSet(this (int value, bool valid) data, int[] bits, Action action)
{
if (data.valid)
{
data.valid = AreBitsSet(data.value, bits);
if (data.valid) action();
}
return data;
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以像这样链接它们:
int num = 5;
num.CallActionIfBitsSet(new[] {1, 3, 5}, () =>
{
/* action */
})
.CallActionIfBitsSet(new[] {2, 3, 4}, () =>
{
/* other action */
})
.CallActionIfBitsSet(new[] {2, 3, 6}, () =>
{
/* other action */
});
Run Code Online (Sandbox Code Playgroud)
我个人不是一个大粉丝,因为我认为与传统的相比,您的界面不会以这种方式变得更容易if,但它会起作用。