I have the following code sample, where the only difference between the 2 parts of the If statement is the less than/greater than operators.
Is there a better way to write this? Could almost do with being able to define an Operator variable.
If myVar = true Then
Do While (X < Y)
'call Method A
开发者_C百科 'the values of X and Y will change within this loop
Loop
Else
Do While (X > Y)
'call Method A
'the values of X and Y will change within this loop
Loop
End If
thanks
You can use the ternary conditional operator, If
, as of VB 2008:
Do While (If(myVar, X < Y, X > Y)))
'call Method A
Loop
However, this will check myVar
on every iteration instead of just once, which is bad for performance.
Dim from As Integer = CInt(iif(myVar, x, y))
Dim until As Integer = CInt(iif(myVar, y, x))
While from < until
'call Method A
End While
Or if 2008 or newer, as Samir says, use the ternary conditional operator to avoid the CInt casts.
You can use a delegate:
Public Function LessThan(Of T As IComparable)(ByVal A As T, ByVal B As T) As Boolean
Return A.CompareTo(B) < 0
End Function
Public Function GreaterThan(Of T AS IComparable)(ByVal A As T, ByVal B As T) As Boolean
Return A.CompareTo(B) > 0
End Function
Dim comparer As Func(Of Integer,Integer,Boolean) = AddressOf GreaterThan(Of Integer)
If myVar Then comparer = AddressOf LessThan(Of Integer)
Do While comparer(X,Y)
''#call Method A
''#the values of X and Y will change within this loop
Loop
Of course, that needs VS2008. For more fun:
Do While CBool(Y.CompareTo(Y) * -1) = myVar
''#...
End While
Do While ((myVar And X < Y) Or (Not myVar And X > Y))
' call Method A
Loop
精彩评论