委派 (F#)

委派表示函式呼叫做為 物件。 在 F# 中,您通常應該使用函式值將函式表示為第一級值;不過,委派會用於.NET Framework,因此當您與預期它們的 API 交互操作時需要委派。 撰寫設計供其他.NET Framework語言使用的程式庫時,也可以使用它們。

語法

type delegate-typename = delegate of type1 -> type2

備註

在上一個語法中, type1 表示引數類型或型別,並 type2 表示傳回型別。 所 type1 代表的引數類型會自動經過 curried。 這表示,如果目標函式的引數經過 curried,而且已位於 Tuple 表單中的引數,則針對此類型使用 Tuple 表單的括弧化 Tuple。 自動 Currying 會移除一組括弧,並保留符合目標方法的 Tuple 引數。 請參閱程式碼範例,以瞭解您應該在每個案例中使用的語法。

委派可以附加至 F# 函式值,以及靜態或實例方法。 F# 函式值可以直接當做引數傳遞至委派建構函式。 針對靜態方法,您可以使用 類別的名稱和 方法來建構委派。 針對實例方法,您會在一個引數中提供物件實例和方法。 在這兩種情況下,都會使用成員存取運算子 (.) 。

委派 Invoke 類型上的 方法會呼叫封裝的函式。 此外,藉由參考 Invoke 方法名稱而不加上括弧,即可將委派當做函式值傳遞。

下列程式碼顯示用來建立代表類別中各種方法之委派的語法。 根據方法是靜態方法還是實例方法,以及它是否有元組形式或 curried 格式的引數,宣告和指派委派的語法稍有不同。

type Test1() =
  static member add(a : int, b : int) =
     a + b
  static member add2 (a : int) (b : int) =
     a + b

  member x.Add(a : int, b : int) =
     a + b
  member x.Add2 (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(Test1.add)
let del2 = Delegate2(Test1.add2)

let testObject = Test1()

// For instance methods, use the instance value name, the dot operator, and the instance method name.
let del3 = Delegate1(testObject.Add)
let del4 = Delegate2(testObject.Add2)

for (a, b) in [ (100, 200); (10, 20) ] 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)

下列程式碼顯示一些您可以使用委派的不同方式。

type Delegate1 = delegate of int * char -> string

let replicate n c = String.replicate n (string c)

// An F# function value constructed from an unapplied let-bound function
let function1 = replicate

// A delegate object constructed from an F# function value
let delObject = Delegate1(function1)

// An F# function value constructed from an unapplied .NET member
let functionValue = delObject.Invoke

List.map (fun c -> functionValue(5,c)) ['a'; 'b'; 'c']
|> List.iter (printfn "%s")

// Or if you want to get back the same curried signature
let replicate' n c =  delObject.Invoke(n,c)

// You can pass a lambda expression as an argument to a function expecting a compatible delegate type
// System.Array.ConvertAll takes an array and a converter delegate that transforms an element from
// one type to another according to a specified function.
let stringArray = System.Array.ConvertAll([|'a';'b'|], fun c -> replicate' 3 c)
printfn "%A" stringArray

上述程式碼範例的輸出如下所示。

aaaaa
bbbbb
ccccc
[|"aaa"; "bbb"|]

另請參閱