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

后端 未结 10 2060
一个人的身影
一个人的身影 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:37

    Else if will only be evaluated if the first condition wasn't true. But two consecutive if statements will both be evaluated.

    You can easily test this concept in a Python interpreter:

    First run this:

    Note: In Python elif is used instead of else if

    a = 1
    if a >= 1:
      print('a is greater than or equal to 1')
    elif a<=1:
      print('a is less than or equal to 1')
    

    then run this

    a=1
    if a >= 1:
      print('a is greater than or equal to 1')
    if a<=1:
      print('a is less than or equal to 1')
    

提交回复
热议问题