F# - 委託



委託是一種引用型別變數,它儲存對方法的引用。該引用可以在執行時更改。F#委託類似於C或C++中指向函式的指標。

宣告委託

委託聲明確定可以由委託引用的方法。委託可以引用具有與委託相同簽名的方法。

委託宣告的語法如下:

type delegate-typename = delegate of type1 -> type2

例如,考慮以下委託:

// Delegate1 works with tuple arguments.
type Delegate1 = delegate of (int * int) -> int

// Delegate2 works with curried arguments.
type Delegate2 = delegate of int * int -> int

這兩個委託都可以用來引用任何具有兩個int引數並返回int型別變數的方法。

在語法中:

  • type1 表示引數型別。

  • type2 表示返回型別。

請注意:

  • 引數型別會自動進行柯里化。

  • 委託可以附加到函式值以及靜態或例項方法。

  • F#函式值可以直接作為引數傳遞給委託建構函式。

  • 對於靜態方法,透過使用類名和方法名來呼叫委託。對於例項方法,則使用物件例項名和方法名。

  • 委託型別的Invoke方法呼叫封裝的函式。

  • 此外,可以透過引用Invoke方法名(不帶括號)將委託作為函式值傳遞。

以下示例演示了這個概念:

示例

type Myclass() =
   static member add(a : int, b : int) =
      a + b
   static member sub (a : int) (b : int) =
      a - b
   member x.Add(a : int, b : int) =
      a + b
   member x.Sub(a : int) (b : int) =
      a - b

// Delegate1 works with tuple arguments.
type Delegate1 = delegate of (int * int) -> int

// Delegate2 works with curried arguments.
type Delegate2 = delegate of int * int -> int

let InvokeDelegate1 (dlg : Delegate1) (a : int) (b: int) =
   dlg.Invoke(a, b)
let InvokeDelegate2 (dlg : Delegate2) (a : int) (b: int) =
   dlg.Invoke(a, b)

// For static methods, use the class name, the dot operator, and the
// name of the static method.
let del1 : Delegate1 = new Delegate1( Myclass.add )
let del2 : Delegate2 = new Delegate2( Myclass.sub )
let mc = Myclass()

// For instance methods, use the instance value name, the dot operator, 
// and the instance method name.

let del3 : Delegate1 = new Delegate1( mc.Add )
let del4 : Delegate2 = new Delegate2( mc.Sub )

for (a, b) in [ (400, 200); (100, 45) ] do
   printfn "%d + %d = %d" a b (InvokeDelegate1 del1 a b)
   printfn "%d - %d = %d" a b (InvokeDelegate2 del2 a b)
   printfn "%d + %d = %d" a b (InvokeDelegate1 del3 a b)
   printfn "%d - %d = %d" a b (InvokeDelegate2 del4 a b)

編譯並執行程式後,將產生以下輸出:

400 + 200 = 600
400 - 200 = 200
400 + 200 = 600
400 - 200 = 200
100 + 45 = 145
100 - 45 = 55
100 + 45 = 145
100 - 45 = 55
廣告
© . All rights reserved.