Nested inline if statement

China☆狼群 提交于 2019-12-12 03:47:31

问题


In VB .Net it is possible to use inline If statements, like this

if a Then ret = "A" Else ret = "Not A"

I know it is also possible to nest these statements. I know this might not be good practice as readability drops down...

If a Then If b Then ret = "A & B" Else ret = "A & Not B" Else ret = "Not A"

which will be evaluated like this :

If a Then
    If b Then
        ret = "A & B"
    Else
        ret = "A & Not B"
    End If
Else
    ret = "Not A"
End If

Now if I remove the last Else statement, I get this :

If a Then If b Then ret = "A & B" Else ret = "A & Not B"

which is :

If a Then
    If b Then
        ret = "A & B"
    Else
        ret = "A & Not B"
    End If
End If

So I guess the compiler finds the Else and matches it to the last openend If in the line, which makes sense. My question is : Is it possible to change the evaluation order ? By that I mean is it possible that the Else is matched with the first if ?

So it would look like this :

If a Then
    If b Then
        ret = "A & B"
    End If
Else
    ret = "Not A"
End If

But inlined (something like this, parenthesis added to understand what I mean) :

If a Then ( If b Then ret = "A & B" ) Else ret = "Not A"

I tried with parenthesis or adding a End If but it provokes syntax errors, and I couldn't find documentation for this.

I'm not stuck anywhere and I know this might not be a good prorgamming practice, but I just wanted to know (out of curiosity) if it was possible.

I know also I could switch the statements (i.e. test b before a), but let's say I can't (a is a List and must be tested for Nothing before b which would be the Count for example).


回答1:


You could do it like this

ret = If(a, If(b, "A & B", "A & Not B"), "Not A")

Personally, I never understood the need to put everything in one line.




回答2:


You may find that this is what you need:

If a And B Then

   ret = "A & B"

Else

   ret = "Not A"

End If

Or as a single line:

If A And B Then Ret = "A & B" Else RET = "Not A"



回答3:


I just created a simple console application with your final nested if statement and it worked fine

Sub Main()
    Dim a = False
    Dim b = True
    If a Then
        If b Then
            Console.WriteLine("A & B")
        End If
    Else
        Console.WriteLine("A & Not B")
    End If
    Console.ReadLine()
End Sub


来源:https://stackoverflow.com/questions/40530315/nested-inline-if-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!