5

評価時間を考えると、次の2つは同等ですか?

if(condition1)
{
    //code1
}
else
{
    //code2
}

condition1 ? code1 : code2

それとも構文的に違うだけですか?

4

4 に答える 4

11

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.

于 2009-11-02T08:26:16.083 に答える
4

code1ええと...前者の場合、との代わりに任意の量またはタイプ(式とステートメント)のコードを使用できますcode2。後者の場合、それらは有効な式でなければなりません。

于 2009-11-02T08:16:11.300 に答える
3

はいはい。

唯一の利益は、コード行を節約することです。

于 2009-11-02T08:15:27.337 に答える
1

はい、これらは2つの異なる構文形式であり、同じように機能し、最も可能性の高い同じコードがコンパイラーによって発行されます。

于 2009-11-02T08:16:49.977 に答える