“else if()” versus multiple “if()”s in C#

后端 未结 10 2066
一个人的身影
一个人的身影 2021-01-03 21:51

How do these practically differ?

// Approach one
if (x == 1)
    DoSomething();
else if (x == 2)
    DoSomethingElse();

// Approach two
if (x == 1)
    DoSo         


        
10条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-03 22:52

    When you use else statement, only one of the branches will be run (i.e. the first, which meets the if condition). All other if conditions won't even be estimated:

    // approach one
    int x = 1;
    if (x == 1)
        DoSomething(); //only this will be run, even if `DoSomething` changes `x` to 2
    else if (x == 2)
        DoSomethingElse();
    

    While when you don't use it each of them may be run (depending on each of the conditions), i.e. each of them is estimated one by one:

    // approach two
    int x = 1;
    if (x == 1)
        DoSomething();//this is run, as `x` == 1
    if (x == 2)
        DoSomethingElse();//if `DoSomething` changes `x` to 2, this is run as well
    

    So, IL may differ.

提交回复
热议问题