【问题标题】:Using ternary operations to make my code cleaner [closed]使用三元运算使我的代码更干净[关闭]
【发布时间】:2021-03-11 22:46:12
【问题描述】:
我一直在做一些 C# 练习题,我想开始玩三元运算以使我的代码更干净。
这是我的代码:
public static string Bomb(string txt)
{
txt.ToLower().Contains("bomb") == true ? "Duck!!!" : "There is no bomb, relax.";
}
所以基本上如果 Bomb("xxxxxx") 包含字符串 "bomb" 它会返回 "Duck!!!"如果没有,它将返回“没有炸弹,放松。”
但由于某种原因,这不起作用,我不知道为什么。
【问题讨论】:
标签:
c#
conditional-operator
【解决方案1】:
您只需添加return
public static string Bomb(string txt)
{
return txt.ToLower().Contains("bomb") == true ? "Duck!!!" : "There is no bomb, relax.";
}
【解决方案2】:
您的三元运算符看起来不错,但是您缺少函数中的 return 语句。还要注意Contains 返回一个布尔值,所以== true 是多余的:
所以我一直在做一些c#练习题,我想开始玩三元运算来让我的代码更干净。
这是我的代码:
public static string Bomb(string txt)
{
return txt.ToLower().Contains("bomb") ? "Duck!!!" : "There is no bomb, relax.";
}
【解决方案3】:
你错过了函数中的返回部分
public static string Bomb(string txt)
{
return txt.ToLower().Contains("bomb") ? "Duck!!!" : "There is no bomb, relax.";
}