我需要在控制台应用程序中处理来自用户的输入,我只需要允许Z字段编号(...,-1,0,1,...)。
我已经用来自用户的char构建了该进程char,通过保留最后一个char我可以验证订单是否正确。最后,用户必须输入一组Z数,例如
-3 6 7 101 -500
。
我的问题是LastInput
与enum
的比较,这意味着我想检查最后一个输入是Numeric | Space | ...
,请查看代码。
public void Foo()
{
ConsoleKeyInfo key;
var chars = new List<char>();
NextChar last = NextChar.Space;
var list = new List<NextChar> {last};
do
{
key = Console.ReadKey(true);
NextChar next = ProcessCharInput(key.KeyChar);
switch (next)
{
case NextChar.None:
if(key.Key != ConsoleKey.Enter)
{
return;
}
continue;
case NextChar.Space:
if (last == (NextChar.Numeric))
{
Console.Write(key.KeyChar);
last = next;
chars.Add(key.KeyChar);
}
break;
case NextChar.Minus:
if (last == (NextChar.Space))
{
Console.Write(key.KeyChar);
last = next;
chars.Add(key.KeyChar);
}
break;
case NextChar.Numeric:
if (last == (NextChar.Numeric | NextChar.Minus | NextChar.Space))
{
Console.Write(key.KeyChar);
last = next;
chars.Add(key.KeyChar);
}
break;
default:
throw new ArgumentOutOfRangeException();
}
}
while (true);
}
[Flags]
private enum NextChar
{
None = 0x0,
Space = 0x1,
Minus = 0x2,
Numeric = 0x4
}
我猜我在使用枚举时出错了,因为Numeric
的输入和Space
的输入不能使last == (NextChar.Numeric | NextChar.Minus | NextChar.Space)
成为真。
答案 0 :(得分:3)
你确定要尝试按位OR吗?
0100 OR 0010 OR 0001 = 0111
这似乎没有帮助。你好像在这里试图做布尔逻辑。在这种情况下,您需要更改
last == (NextChar.Numeric | NextChar.Minus | NextChar.Space)
到
last == NextChar.Numeric || last == NextChar.Minus || last == NextChar.Space
...当然,老实说,如果你被限制在一组4个值中并且你试图确保你对其中的3个做某些事情,你可能会更加清晰和富有表现力
if(last != NextChar.None)
答案 1 :(得分:2)
以下几行说明了如何解释:
last == (NextChar.Numeric | NextChar.Minus | NextChar.Space)
last == (4 | 2 | 1) // Same meaning with the constants in place.
last == 7 // Same meaning, with the or calculated.
你想要的可能是:
last == NextChar.Numeric || last == NextChar.Minus || last == NextChar.Space
或按位逻辑:
last & (NextChar.Numeric | NextChar.Minus | NextChar.Space) != 0
答案 2 :(得分:2)
要用于位标志的一般模式是<comparison value> <operation> (value & mask))
。特别针对您的情况:
if(NextChar.None != (last & (NextChar.Numeric | NextChar.Minus | NextChar.Space))) { ... }