gpt4 book ai didi

C# 语法 if (value=this || this|| this) do this

转载 作者:行者123 更新时间:2023-11-30 13:08:17 25 4
gpt4 key购买 nike

只是把一些代码放在那里

string answer = "hotel"
if (answer == "house"|| answer == "hotel" || answer =="appartment")
{
DoSomething()
}

我想知道是否有什么方法可以将它缩短为

string answer = "hotel"
if (answer == "house"|| "hotel" || "appartment")
{
DoSomething()
}

我知道switch语句

switch (answer)
{
case "house":
case "hotel":
case "appartment": DoSomething();
break;
default :DoNothing();
}

我只是想知道是否有像我上面描述的那样的语法糖。

最佳答案

可以为此使用一些语法糖:

if((new[]{"house", "hotel", "apartment"}).Contains(answer))
{
}

请注意,这将即时创建一个新数组,因此可能比仅检查 Boolean 更昂贵。

关于C# 语法 if (value=this || this|| this) do this,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10499133/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com