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.