2010-04-19 30 views
2

我有以下代碼示例,其中If語句的2個部分之間的唯一區別是小於/大於運算符。如何編寫2個語句,這些語句在VB.NET中僅由操作符類型區分

有沒有更好的方法來寫這個?幾乎可以做到定義一個Operator變量。

 If myVar = true Then 

      Do While (X < Y) 
       'call Method A 
       '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 

感謝

+0

除了源代碼的行數你可能是最快的。 iif和if()是非常緩慢的。 – dbasnett 2010-04-19 12:29:43

+0

@dbasnett - 你是指If()運算符還是If()函數?如果前者,你能提供一個鏈接來詳細說明If()運算符的性能問題嗎? – 2010-04-19 16:50:42

回答

2

可以使用三元條件操作,If,截至2008年VB的:

Do While (If(myVar, X < Y, X > Y))) 
    'call Method A 
Loop 

然而,這將在每次迭代檢查myVar,而不是隻有一次,這對性能不利。

+0

謝謝 - 我不認爲這裏的性能問題太多,因爲X和Y的值總是小於10! 這在VS 2008中編譯,針對.NET 2.0,但不針對.NET 2.0針對VS 2005 - 你知道爲什麼嗎? – 2010-04-19 13:26:55

+0

在VS2005中,您必須使用Iif運算符(並將其轉換爲CInt)。你可以在我的答案中看到一個樣本。 – 2010-04-19 13:29:54

+1

@Richard:我會推薦@ ho的回答。它效率更高。 – 2010-04-19 13:47:04

0
Do While ((myVar And X < Y) Or (Not myVar And X > Y)) 
    ' call Method A 
Loop 
2
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 

或者如果2008年或更新,如Samir所說,使用三元條件運算符來避免CInt投。

+0

這個答案很好 - 它避免了潛在的性能問題,並且仍然非常易讀。 – 2010-04-19 13:44:52

+0

好的答案,但不幸的是,在這種情況下,X和Y的值將在While循環內發生變化(對不起,忘了提及第一次!) – 2010-04-19 13:45:32

+0

@Richard您可以設置「from」和「直到「在循環中 – 2010-04-19 14:01:10

1

您可以使用委託:

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 

當然,需要VS2008。更多的樂趣:

Do While CBool(Y.CompareTo(Y) * -1) = myVar 
    ''#... 
End While 
+0

的確有趣的答案!我以前沒有見過Func Delegate,但看起來我必須等到我的應用程序從.NET 2.0開始運行。 我會記住這一點,以後感謝 – 2010-04-19 14:20:03

+0

@Richard - 您可以在.Net 2.0中爲自己定義Func委託 – 2010-04-19 16:09:27