英文:
Use pattern mattching to detect x is not a or not b
问题
我需要检查某个值是否不是一个或另一个值,并且我想要在模式匹配中使用 or
。 "forward" 的情况 - x is a o b
很容易:
int GetInt() => 3;
if (GetInt() is 3 or 4)
{
Console.WriteLine("3 or 4");
}
但是否定的情况我想不出来。我尝试过:
if (GetInt() is not 4 or 3)
{
Console.WriteLine("not 3 or 4 #1");
}
else
{
Console.WriteLine("Succcess");
}
或者
if (GetInt() is not 3 or not 4)
{
Console.WriteLine("not 3 or 4 #2");
}
else
{
Console.WriteLine("Succcess");
}
但两者都会打印第一个语句(not 3 or 4...
)。
此外,IDE 会将代码的不同部分变灰:
和
英文:
I need to check if some value is not one or another and I want to use or
with pattern matching. The "forward" one - x is a o b
is easy:
int GetInt() => 3;
if (GetInt() is 3 or 4)
{
Console.WriteLine("3 or 4");
}
But negation I can't figure out. I tried:
if (GetInt() is not 4 or 3)
{
Console.WriteLine("not 3 or 4 #1");
}
else
{
Console.WriteLine("Succcess");
}
Or
if (GetInt() is not 3 or not 4)
{
Console.WriteLine("not 3 or 4 #2");
}
else
{
Console.WriteLine("Succcess");
}
But both print the first statement (the not 3 or 4...
).
Also IDE grays out different parts of the code:
and
答案1
得分: 2
你可以只使用括号:
if (GetInt() 不是 (3 或 4))
{
Console.WriteLine("不是 3 或 4 #2");
}
else
{
Console.WriteLine("成功");
}
演示 @sharplab.io
英文:
You can just use parenthesis:
if (GetInt() is not (3 or 4))
{
Console.WriteLine("not 3 or 4 #2");
}
else
{
Console.WriteLine("Success");
}
Demo @sharplab.io
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论