Delegaty (F#)

Delegat reprezentuje wywołanie funkcji jako obiekt. W języku F#zwykle należy używać wartości funkcji do reprezentowania funkcji jako wartości pierwszej klasy; jednak delegaty są używane w programie .NET Framework i dlatego są potrzebne podczas współdziałania z interfejsami API, które ich oczekują. Mogą być one również używane podczas tworzenia bibliotek przeznaczonych do użytku z innych języków programu .NET Framework.

Składnia

type delegate-typename = delegate of type1 -> type2

Uwagi

W poprzedniej składni type1 reprezentuje typ argumentu lub typy i type2 reprezentuje typ zwracany. Typy argumentów reprezentowane przez type1 program są automatycznie curried. Sugeruje to, że w przypadku tego typu należy użyć formularza krotki, jeśli argumenty funkcji docelowej są curried i nawias krotki dla argumentów, które znajdują się już w formularzu krotki. Automatyczne currying usuwa zestaw nawiasów, pozostawiając argument krotki pasujący do metody docelowej. Zapoznaj się z przykładem kodu składni, której należy użyć w każdym przypadku.

Delegaci mogą być dołączani do wartości funkcji języka F# oraz metod statycznych lub metod wystąpień. Wartości funkcji języka F# można przekazywać bezpośrednio jako argumenty do delegowania konstruktorów. W przypadku metody statycznej należy skonstruować delegata przy użyciu nazwy klasy i metody. W przypadku metody wystąpienia należy podać wystąpienie obiektu i metodę w jednym argumencie. W obu przypadkach jest używany operator dostępu do składowych (.).

Metoda Invoke w typie delegata wywołuje hermetyzowaną funkcję. Ponadto delegaci mogą być przekazywane jako wartości funkcji, odwołując się do nazwy metody Invoke bez nawiasów.

Poniższy kod przedstawia składnię tworzenia delegatów reprezentujących różne metody w klasie. W zależności od tego, czy metoda jest metodą statyczną, czy metodą wystąpienia i czy ma argumenty w formularzu krotki, czy w postaci curried, składnia deklarowania i przypisywania delegata jest nieco inna.

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)

Poniższy kod przedstawia niektóre z różnych sposobów pracy z delegatami.

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

Dane wyjściowe poprzedniego przykładu kodu są następujące.

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

Nazwy można dodawać do parametrów delegowanych w następujący sposób:

// http://www.pinvoke.net/default.aspx/user32/WinEventDelegate.html
type WinEventDelegate = delegate of hWinEventHook:nativeint * eventType:uint32 * hWnd:nativeint * idObject:int * idChild:int * dwEventThread:uint32 * dwmsEventTime:uint32 -> unit

Nazwy parametrów delegowanych są opcjonalne i będą wyświetlane w metodzie Invoke . Nie są one wymagane do dopasowania nazw parametrów w implementacji. Są one dozwolone tylko dla formy curried, ale nie formy tupled.

type D1 = delegate of item1: int * item2: string -> unit
let a = D1(fun a b -> printf "%s" b)
a.Invoke(item2 = "a", item1 = 1) // Calling with named arguments

type D2 = delegate of int * item2: string -> unit // Omitting one name
let b = D2(fun a b -> printf "%s" b)
b.Invoke(1, item2 = "a")

Dane wyjściowe poprzedniego przykładu kodu są następujące.

aa

Zobacz też