對不起,代碼塊越長,但我想用lambda表達式和匿名函數來演示可用的不同選項。
首先,我們將創建一些基本的功能一起玩......
'Solves a basic linear equation y(x) = ax + b, given a, b, and x.
Function Linear(a As Double, b As Double, x As Double) As Double
Return a * x + b
End Function
'Return the inverse of a number (i.e. y(x) = -x)
Function Inverse(x As Double) As Double
Return -x
End Function
而這需要一個函數的函數。
'To help differentiate the type of the parameter from the return type,
'I'm being generic with the return type. This function takes any function
'that takes a double and returns some generic type, T.
Public Function EvalEquation(Of T)(x As Double, equation As Func(Of Double, T)) As T
Return equation(x)
End Function
最後,我們將使用它!
'The closest thing to a functor is probably the AddressOf keyword.
For x = 0 To 10
Dim answer = EvalEquation(x, AddressOf Inverse)
'Do something
Next
但AddressOf有一些限制...EvalEquationForX需要一個只帶一個參數的函數,因此我不能簡單地使用AddressOf,因爲我不能傳遞額外的參數。但是,我可以動態創建一個可以爲我做的功能。
For x = 0 To 10
Dim answer = EvalEquation(x, Function(x)
Dim a = 1
Dim b = 0
Return Linear(a, b, x)
End Function)
'Do something
Next
我要指出,你可以定義一個Func(Of T1, T2, T3, T4,... TResult)
,所以你可以創建一個可以採取兩個參數並使用它的功能。
Public Function EvalEquationWithTwoParameters(Of T)(
a As Double, b As Double, x As Double,
equation As Func(Of Double, Double, Double, T)) As T
Return equation(a, b, x)
End Function
而且使用這樣的:
For x = 0 To 10
Dim answer = EvalEquationWithTwoParameters(1, 0, x, AddressOf Linear)
'Do something
Next
希望幫助!