是否可以用三元运算符(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
不。三元运算符仅根据条件返回两个潜在值中的一个。
您可以使用三元运算符执行以下操作:
int a = condition ? 0 : 2
,这将根据 a
的值,为变量 condition
分配 0 或 2 的值。
给出一个更完整的示例来说明您打算做什么,这里的某人可能会想出更好的语法。
试试这个
return condition? true: false;