使用模式匹配来检测 x 不是 a 或不是 b。

huangapple go评论62阅读模式
英文:

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 会将代码的不同部分变灰:

使用模式匹配来检测 x 不是 a 或不是 b。

使用模式匹配来检测 x 不是 a 或不是 b。

英文:

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:

使用模式匹配来检测 x 不是 a 或不是 b。

and

使用模式匹配来检测 x 不是 a 或不是 b。

答案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

huangapple
  • 本文由 发表于 2023年5月25日 07:05:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/76327918.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定