評価時間を考えると、次の2つは同等ですか?
if(condition1)
{
//code1
}
else
{
//code2
}
condition1 ? code1 : code2
それとも構文的に違うだけですか?
評価時間を考えると、次の2つは同等ですか?
if(condition1)
{
//code1
}
else
{
//code2
}
condition1 ? code1 : code2
それとも構文的に違うだけですか?
The difference is that the latter station can be used to return a value based on a condition.
For example, if you have a following statement:
if (SomeCondition())
{
text = "Yes";
}
else
{
text = "No";
}
Using a ternary operator, you will write:
text = SomeCondition() ? "Yes" : "No";
Note how the first example executes a statement based on a condition, while the second one returns a value based on a condition.
code1
ええと...前者の場合、との代わりに任意の量またはタイプ(式とステートメント)のコードを使用できますcode2
。後者の場合、それらは有効な式でなければなりません。
はいはい。
唯一の利益は、コード行を節約することです。
はい、これらは2つの異なる構文形式であり、同じように機能し、最も可能性の高い同じコードがコンパイラーによって発行されます。