2016-05-13 77 views
0

我希望代碼返回運算符(如(+)或( - ) ),然後使用它來執行計算。在vb.net中可能嗎?vb.net函數返回運算符

public function rOperator(params) as operator 

if (..) 
return + 

else 
return - 
end if 

end function 

Msgbox(1 rOperator 2) 
+0

不,這是不可能的。最簡單的方法是根據你的情況製作一個不同的計算函數。即'DoMath(1,2)' –

回答

2

前面已經講過,這是不可能的。你可以做的是創建一個Func(Of T)字典,然後通過傳入您的運營商來調用這些字段:

Sub Main 
    Dim operations As New Dictionary(Of String, Func(Of Double, Double, Double))() 

    'Set up operations for addition, subtractions, multipication, and division 
    operations.Add("+", Function(l, r) l + r) 
    operations.Add("-", Function(l, r) l - r) 
    operations.Add("*", Function(l, r) l * r) 
    operations.Add("/", Function(l, r) l/r) 

    Dim result As Double = operations("+")(5, 5) 
    Dim result2 As Double = operations("*")(5, 5) 

    Console.WriteLine(result) 
    Console.WriteLine(result2) 

End Sub