三元运算符? [英] Ternary Operator ?
问题描述
我有两种方法可以得到结果吗?
例如三元运算符
字符串mystring =(textbox1.Text ==")? "X"一些布尔== true:"O";
请帮忙???
两个结果"X"和Somebool是结果
Is there a way for me to have two results
for a ternary Operator for Example
string mystring = (textbox1.Text == "")? "X" some bool == true :"O";
help please ???
two results "X" and Somebool being the results
推荐答案
否.这等效于if
-else
运算符,有两种选择.您总是返回一个或另一个结果,而不会两者都返回.
—SA
No. This is equivalent toif
-else
operator with exactly two alternatives. You always return one result or another, never both.
—SA
您可以测试2个条件,并得出2种可能的结果:
You can test 2 conditions and have 2 possible results with that:
string mystring = textbox1.Text == "" && some_bool == true ? "X" : "O";
在这种情况下,如果同时满足两个条件,mystring
将为"X",否则为"0"(1或不满足条件)
或者,您可以进行2次测试,并得到3个结果,如下所示:
In that case mystring
will be "X" if both conditions are met and "0" otherwise (1 or no condition met)
Or you can do 2 test and have 3 results like this:
string mystring = textbox1.Text == "" ? "X" : some_bool ? "*" : "0";
在这种情况下,如果字符串为空,则mystring
将为"X".否则,如果some_bool
为true,则为"*";否则为"O".
在C ++中,可以使用逗号运算符设置2个值,但这在C#中无效.无论如何,不建议使用这种构造,因为它会使代码的可维护性降低.
In that case mystring
will be "X" if the string is empty. Otherwise, it will be "*" if some_bool
is true and "O" if not.
In C++, it would be possible to set 2 values using comma operator but this is not valid in C#. Anyway, such construct are not recommended as it make the code less maintainable.
// Only in C++
bool some_bool = false;
String ^mystring = textbox1.Text == String::Empty ? (some_bool = true, "X") : "O";
如果字符串为空,则mystring
和some_bool
都将被更新.这不会在C#中编译(即使删除^后也是如此).
您的问题不清楚...
If the string is empty, then both mystring
and some_bool
would get updated. This does not compile in C# (even after removing the ^).
Your question is not clear...
这篇关于三元运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!