Fsharp-delegates
提供:Dev Guides
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
両方のデリゲートを使用して、2つの_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