是否可以在三元运算符(c# if 的简写)中编写此 if 语句?如果是的话会是什么?
if (condition)
{
return true;
}
else
{
int a = 2;
}
提前谢谢大家。非常感谢你。
对不起,如果我让你感到困惑。我试图在该方法的 if else 块中使用三元运算符。
public static bool CompareDictionary(this Dictionary<Position, char>
dictionary1,
Dictionary<Position, char> dictionary2, out List<string> wordList)
{
string str = "";
wordList = new List<string>();
foreach (var dic1KeyVal in dictionary1)
{
Position d1key = dic1KeyVal.Key;
char d1Pos = dic1KeyVal.Value;
bool isFound = false;
foreach (var dic2KeyVal in dictionary2)
{
Position d2key = dic2KeyVal.Key;
char d2Pos = dic2KeyVal.Value;
if (d1Pos.Equals(d2Pos) && d1key == d2key)
{
isFound = true;
str = str + d1Pos.ToString();
}
}
if (isFound == false)
{
return false;
}
else
{
wordList.Add(str);
str = "";
}
}
return true;
}
最佳答案
简答
不。
长答案
首先,这段代码甚至不需要 else:
if (condition)
{
return true;
}
else
{
int a = 2;
}
并且可以写成:
if (condition)
{
return true;
}
int a = 2;
现在对于三元运算符:三元运算符中的两个条件必须返回相同的内容。您不能在一种情况下返回
bool
,然后在另一种情况下分配给变量。例如,如果您正在检查问题的答案,它将是这样的:return answer == 2 ? true : false;
无论答案是否正确,我们都会返回
bool
。或者它可能是这样的:return answer == 2 ? 1: -1;
但不是这样:
return answer == 2 ? true : "wrong"; // will not compile
关于c# - 如何将c#三元运算符用于return语句与其他语句的结合,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44612649/