Delegate クラス

定義

デリゲートを表します。デリゲートとは、静的メソッドを参照するデータ構造、またはクラス インスタンスおよびクラスのインスタンス メソッドを参照するデータ構造です。

public ref class Delegate abstract
public ref class Delegate abstract : ICloneable, System::Runtime::Serialization::ISerializable
public abstract class Delegate
public abstract class Delegate : ICloneable, System.Runtime.Serialization.ISerializable
[System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.AutoDual)]
[System.Serializable]
public abstract class Delegate : ICloneable, System.Runtime.Serialization.ISerializable
[System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.AutoDual)]
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class Delegate : ICloneable, System.Runtime.Serialization.ISerializable
type Delegate = class
type Delegate = class
    interface ICloneable
    interface ISerializable
[<System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.AutoDual)>]
[<System.Serializable>]
type Delegate = class
    interface ICloneable
    interface ISerializable
[<System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.AutoDual)>]
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type Delegate = class
    interface ICloneable
    interface ISerializable
Public MustInherit Class Delegate
Public MustInherit Class Delegate
Implements ICloneable, ISerializable
継承
Delegate
派生
属性
実装

次の例は、 という名前 myMethodDelegateのデリゲートを定義する方法を示しています。 このデリゲートのインスタンスは、入れ子になったクラスのインスタンス メソッドと静的メソッドに対して作成されます mySampleClass 。 インスタンス メソッドのデリゲートには、 の mySampleClassインスタンスが必要です。 インスタンスは mySampleClass という名前 mySCの変数に保存されます。

using namespace System;
delegate String^ myMethodDelegate( // Declares a delegate for a method that takes in an int and returns a String.
int myInt );

// Defines some methods to which the delegate can point.
ref class mySampleClass
{
public:

   // Defines an instance method.
   String^ myStringMethod( int myInt )
   {
      if ( myInt > 0 )
            return ("positive");

      if ( myInt < 0 )
            return ("negative");

      return ("zero");
   }


   // Defines a static method.
   static String^ mySignMethod( int myInt )
   {
      if ( myInt > 0 )
            return ("+");

      if ( myInt < 0 )
            return ("-");

      return ("");
   }

};

int main()
{
   
   // Creates one delegate for each method. For the instance method, an 
   // instance (mySC) must be supplied. For the static method, only the
   // method name is needed.
   mySampleClass^ mySC = gcnew mySampleClass;
   myMethodDelegate^ myD1 = gcnew myMethodDelegate( mySC, &mySampleClass::myStringMethod );
   myMethodDelegate^ myD2 = gcnew myMethodDelegate( mySampleClass::mySignMethod );
   
   // Invokes the delegates.
   Console::WriteLine( "{0} is {1}; use the sign \"{2}\".", 5, myD1( 5 ), myD2( 5 ) );
   Console::WriteLine( "{0} is {1}; use the sign \"{2}\".",  -3, myD1(  -3 ), myD2(  -3 ) );
   Console::WriteLine( "{0} is {1}; use the sign \"{2}\".", 0, myD1( 0 ), myD2( 0 ) );
}

/*
This code produces the following output:

5 is positive; use the sign "+".
-3 is negative; use the sign "-".
0 is zero; use the sign "".
*/
using System;
public class SamplesDelegate  {

   // Declares a delegate for a method that takes in an int and returns a string.
   public delegate string myMethodDelegate( int myInt );

   // Defines some methods to which the delegate can point.
   public class mySampleClass  {

      // Defines an instance method.
      public string myStringMethod ( int myInt )  {
         if ( myInt > 0 )
            return( "positive" );
         if ( myInt < 0 )
            return( "negative" );
         return ( "zero" );
      }

      // Defines a static method.
      public static string mySignMethod ( int myInt )  {
         if ( myInt > 0 )
            return( "+" );
         if ( myInt < 0 )
            return( "-" );
         return ( "" );
      }
   }

   public static void Main()  {

      // Creates one delegate for each method. For the instance method, an
      // instance (mySC) must be supplied. For the static method, use the
      // class name.
      mySampleClass mySC = new mySampleClass();
      myMethodDelegate myD1 = new myMethodDelegate( mySC.myStringMethod );
      myMethodDelegate myD2 = new myMethodDelegate( mySampleClass.mySignMethod );

      // Invokes the delegates.
      Console.WriteLine( "{0} is {1}; use the sign \"{2}\".", 5, myD1( 5 ), myD2( 5 ) );
      Console.WriteLine( "{0} is {1}; use the sign \"{2}\".", -3, myD1( -3 ), myD2( -3 ) );
      Console.WriteLine( "{0} is {1}; use the sign \"{2}\".", 0, myD1( 0 ), myD2( 0 ) );
   }
}


/*
This code produces the following output:

5 is positive; use the sign "+".
-3 is negative; use the sign "-".
0 is zero; use the sign "".
*/
// Declares a delegate for a method that takes in an int and returns a string.
type MyMethodDelegate = delegate of int -> string

// Defines some methods to which the delegate can point.
type MySampleClass() =
    // Defines an instance method.
    member _.MyStringMethod(myInt) =
        if myInt > 0 then "positive"
        elif myInt < 0 then "negative"
        else "zero"

    // Defines a static method.
    static member MySignMethod(myInt) =
        if myInt > 0 then "+"
        elif myInt < 0 then "-"
        else ""

// Creates one delegate for each method. For the instance method, an
// instance (mySC) must be supplied. For the static method, use the
// class name.
let mySC = MySampleClass()
let myD1 = MyMethodDelegate mySC.MyStringMethod
let myD2 = MyMethodDelegate MySampleClass.MySignMethod

// Invokes the delegates.
printfn $"{5} is {myD1.Invoke 5} use the sign \"{myD2.Invoke 5}\"."
printfn $"{-3} is {myD1.Invoke -3} use the sign \"{myD2.Invoke -3}\"."
printfn $"{0} is {myD1.Invoke 0} use the sign \"{myD2.Invoke 0}\"."

// This code produces the following output:
//     5 is positive use the sign "+".
//     -3 is negative use the sign "-".
//     0 is zero use the sign "".
Public Class SamplesDelegate

   ' Declares a delegate for a method that takes in an int and returns a String.
   Delegate Function myMethodDelegate(myInt As Integer) As [String]

   ' Defines some methods to which the delegate can point.
   Public Class mySampleClass

      ' Defines an instance method.
      Public Function myStringMethod(myInt As Integer) As [String]
         If myInt > 0 Then
            Return "positive"
         End If
         If myInt < 0 Then
            Return "negative"
         End If
         Return "zero"
      End Function 'myStringMethod

      ' Defines a static method.
      Public Shared Function mySignMethod(myInt As Integer) As [String]
         If myInt > 0 Then
            Return "+"
         End If
         If myInt < 0 Then
            Return "-"
         End If
         Return ""
      End Function 'mySignMethod
   End Class

   Public Shared Sub Main()

      ' Creates one delegate for each method. For the instance method, an
      ' instance (mySC) must be supplied. For the Shared method, the
      ' method name is qualified by the class name.
      Dim mySC As New mySampleClass()
      Dim myD1 As New myMethodDelegate(AddressOf mySC.myStringMethod)
      Dim myD2 As New myMethodDelegate(AddressOf mySampleClass.mySignMethod)

      ' Invokes the delegates.
      Console.WriteLine("{0} is {1}; use the sign ""{2}"".", 5, myD1(5), myD2(5))
      Console.WriteLine("{0} is {1}; use the sign ""{2}"".", - 3, myD1(- 3), myD2(- 3))
      Console.WriteLine("{0} is {1}; use the sign ""{2}"".", 0, myD1(0), myD2(0))

   End Sub

End Class


'This code produces the following output:
' 
'5 is positive; use the sign "+".
'-3 is negative; use the sign "-".
'0 is zero; use the sign "".

注釈

クラスは Delegate 、デリゲート型の基本クラスです。 ただし、 クラスまたは MulticastDelegate クラスから明示的に派生できるのは、Delegateシステムとコンパイラだけです。 また、デリゲート型から新しい型を派生させるのも許可されません。 クラスは Delegate デリゲート型とは見なされません。デリゲート型の派生に使用されるクラスです。

ほとんどの言語はキーワード (keyword)をdelegate実装し、それらの言語のコンパイラは クラスからMulticastDelegate派生できるため、ユーザーは言語によって提供されるキーワード (keyword)を使用delegateする必要があります。

Note

共通言語ランタイムは、デリゲートと同じシグネチャを持つ各デリゲート型のメソッドを提供 Invoke します。 コンパイラによって自動的に呼び出されるため、このメソッドを C#、Visual Basic、または Visual C++ から明示的に呼び出す必要はありません。 メソッドは Invoke 、デリゲート型のシグネチャを見つける場合に リフレクション に役立ちます。

共通言語ランタイムは、デリゲート BeginInvoke の非同期呼び出しを有効にするために、 メソッドと EndInvoke メソッドを使用して各デリゲート型を提供します。 これらのメソッドの詳細については、「非同期的に 同期メソッドを呼び出す」を参照してください。

デリゲート型の宣言は、1 つ以上のメソッドのシグネチャを指定するコントラクトを確立します。 デリゲートは、次への参照を持つデリゲート型のインスタンスです。

  • 型のインスタンス メソッドと、その型に割り当て可能なターゲット オブジェクト。

  • 仮パラメーター リストで公開される非表示 this パラメーターを持つ型のインスタンス メソッド。 デリゲートは、開いているインスタンス デリゲートと言われます。

  • 静的メソッド。

  • 静的メソッドと、メソッドの最初のパラメーターに割り当て可能なターゲット オブジェクト。 デリゲートは、最初の引数で閉じられると言われます。

デリゲート バインドの詳細については、 メソッドのオーバーロードに関するページを CreateDelegate(Type, Object, MethodInfo, Boolean) 参照してください。

デリゲートが最初の引数 (最も一般的なケース) で閉じたインスタンス メソッドを表す場合、デリゲートはメソッドのエントリ ポイントへの参照と、ターゲットと呼ばれるオブジェクトへの参照を格納します。これは、メソッドを定義した型に割り当て可能な型です。 デリゲートは、開いているインスタンス メソッドを表す場合、メソッドのエントリ ポイントへの参照を格納します。 デリゲートシグネチャには、仮パラメーター リストに非表示 this パラメーターを含める必要があります。この場合、デリゲートにはターゲット オブジェクトへの参照がないため、デリゲートが呼び出されたときにターゲット オブジェクトを指定する必要があります。

デリゲートが静的メソッドを表す場合、デリゲートはメソッドのエントリ ポイントへの参照を格納します。 デリゲートが最初の引数で閉じられている静的メソッドを表す場合、デリゲートはメソッドのエントリ ポイントへの参照と、メソッドの最初の引数の型に割り当て可能なターゲット オブジェクトへの参照を格納します。 デリゲートが呼び出されると、静的メソッドの最初の引数はターゲット オブジェクトを受け取ります。 この最初の引数は参照型である必要があります。

デリゲートの呼び出しリストは、リストの各要素がデリゲートによって表されるメソッドの 1 つを呼び出す順序付きデリゲートのセットです。 呼び出しリストには、重複するメソッドを含めることができます。 呼び出し中、メソッドは呼び出しリストに表示される順序で呼び出されます。 デリゲートは、その呼び出しリスト内のすべてのメソッドを呼び出そうとします。重複は、呼び出しリストに表示されるたびに 1 回呼び出されます。 デリゲートは不変です。作成されると、デリゲートの呼び出しリストは変更されません。

デリゲートは 1 つ以上のメソッドを呼び出し、操作の組み合わせに使用できるため、デリゲートはマルチキャストまたは結合可能と呼ばれます。

RemoveなどのCombine操作を組み合わせると、既存のデリゲートは変更されません。 代わりに、このような操作は、操作の結果、変更されていないデリゲート、または nullを含む新しいデリゲートを返します。 結合操作は、操作の結果が少なくとも 1 つのメソッドを参照しないデリゲートである場合にを返 null します。 結合操作は、要求された操作に影響がない場合に、変更されていないデリゲートを返します。

Note

マネージド言語では、 メソッドと Remove メソッドをCombine使用してデリゲート操作を実装します。 たとえば、Visual Basic の AddHandler および RemoveHandler ステートメント、C# のデリゲート型の += 演算子と -= 演算子などがあります。

.NET Framework 4 以降では、ジェネリック デリゲート型にバリアント型パラメーターを指定できます。 反変型パラメーターはデリゲートのパラメーター型として使用でき、共変型パラメーターは戻り値の型として使用できます。 この機能を使用すると、同じジェネリック型定義から構築されたジェネリック デリゲート型は、共 変性と反変性で説明されているように、型引数が継承関係を持つ参照型である場合に割り当て互換性があります。

Note

分散のために割り当て互換である汎用デリゲートは、必ずしも組み合わせ可能ではありません。 組み合わせ可能にするには、型が正確に一致している必要があります。 たとえば、 という名前のクラスが という名前 Derived のクラスから派生しているとします Base。 型 Action<Base> のデリゲート (Action(Of Base) Visual Basic では) を 型の変数に割り当てることができますが、型 Action<Derived>が完全に一致しないため、2 つのデリゲートを結合することはできません。

呼び出されたメソッドが例外をスローした場合、メソッドは実行を停止し、例外はデリゲートの呼び出し元に返され、呼び出しリスト内の残りのメソッドは呼び出されません。 呼び出し元で例外をキャッチしても、この動作は変更されません。

デリゲートによって呼び出されたメソッドのシグネチャに戻り値が含まれている場合、デリゲートは呼び出しリストの最後の要素の戻り値を返します。 シグネチャに参照渡しされるパラメーターが含まれている場合、パラメーターの最終的な値は、呼び出しリスト内のすべてのメソッドが順番に実行され、パラメーターの値が更新された結果になります。

C のデリゲートに最も近いのは、関数ポインターです。 デリゲートは、静的メソッドまたはインスタンス メソッドを表すことができます。 デリゲートがインスタンス メソッドを表す場合、デリゲートはメソッドのエントリ ポイントへの参照だけでなく、クラス インスタンスへの参照も格納します。 関数ポインターとは異なり、デリゲートはオブジェクト指向であり、型セーフです。

コンストラクター

Delegate(Object, String)

指定したインスタンス メソッドを指定のクラス インスタンスに対して呼び出すデリゲートを初期化します。

Delegate(Type, String)

指定したクラスから指定の静的メソッドを呼び出すデリゲートを初期化します。

プロパティ

Method

デリゲートによって表されるメソッドを取得します。

Target

現在のデリゲートがインスタンス メソッドを呼び出す対象のクラス インスタンスを取得します。

メソッド

Clone()

デリゲートの簡易コピーを作成します。

Combine(Delegate, Delegate)

2 つのデリゲートの呼び出しリストを連結します。

Combine(Delegate[])

デリゲートの配列の呼び出しリストを連結します。

CombineImpl(Delegate)

指定したマルチキャスト (組み合わせ可能) デリゲートと現在のマルチキャスト (組み合わせ可能) デリゲートの呼び出しリストを連結します。

CreateDelegate(Type, MethodInfo)

指定したメソッドを表す、指定した型のデリゲートを作成します。

CreateDelegate(Type, MethodInfo, Boolean)

指定された静的メソッドを表す、指定された型のデリゲートを、バインドに失敗した場合の動作を指定して作成します。

CreateDelegate(Type, Object, MethodInfo)

指定された静的メソッドまたはインスタンス メソッドを表す、指定した型のデリゲートを、第 1 引数を指定して作成します。

CreateDelegate(Type, Object, MethodInfo, Boolean)

指定された静的メソッドまたはインスタンス メソッドを表す、指定した型のデリゲートを、第 1 引数およびバインドに失敗したときの動作を指定して作成します。

CreateDelegate(Type, Object, String)

指定したクラス インスタンスに対して呼び出す指定したインスタンス メソッドを表す、指定した型のデリゲートを作成します。

CreateDelegate(Type, Object, String, Boolean)

大文字と小文字の区別方法を指定して、指定したクラス インスタンスに対して呼び出す指定した型のデリゲートを作成します。

CreateDelegate(Type, Object, String, Boolean, Boolean)

大文字と小文字の区別方法およびバインドに失敗したときの動作を指定して、指定したクラス インスタンスに対して呼び出す指定した型のデリゲートを作成します。

CreateDelegate(Type, Type, String)

指定したクラスの指定した静的メソッドを表す、指定した型のデリゲートを作成します。

CreateDelegate(Type, Type, String, Boolean)

指定したクラスの指定した静的メソッドを表す、指定した型のデリゲートを、大文字と小文字の区別方法を指定して作成します。

CreateDelegate(Type, Type, String, Boolean, Boolean)

大文字と小文字の区別方法およびバインドに失敗したときの動作を指定して、指定したクラスの指定した静的メソッドを表す、指定した型のデリゲートを作成します。

DynamicInvoke(Object[])

現在のデリゲートが表すメソッドを動的に呼び出します (遅延バインディング)。

DynamicInvokeImpl(Object[])

現在のデリゲートが表すメソッドを動的に呼び出します (遅延バインディング)。

Equals(Object)

指定したオブジェクトと現在のデリゲートが同じ型を持ち、同じターゲット、メソッド、および呼び出しリストを共有しているかどうかを確認します。

GetHashCode()

デリゲートのハッシュ コードを返します。

GetInvocationList()

デリゲートの呼び出しリストを返します。

GetMethodImpl()

現在のデリゲートによって表されるメソッドを取得します。

GetObjectData(SerializationInfo, StreamingContext)
互換性のために残されています。

サポートされていません。

GetType()

現在のインスタンスの Type を取得します。

(継承元 Object)
MemberwiseClone()

現在の Object の簡易コピーを作成します。

(継承元 Object)
Remove(Delegate, Delegate)

一方のデリゲートの呼び出しリストから、最後に出現した他方のデリゲートの呼び出しリストを削除します。

RemoveAll(Delegate, Delegate)

一方のデリゲートの呼び出しリストから、そこに出現する他方のデリゲートの呼び出しリストをすべて削除します。

RemoveImpl(Delegate)

一方のデリゲートの呼び出しリストから、他方のデリゲートの呼び出しリストを削除します。

ToString()

現在のオブジェクトを表す文字列を返します。

(継承元 Object)

演算子

Equality(Delegate, Delegate)

指定したデリゲートが等しいかどうかを判断します。

Inequality(Delegate, Delegate)

指定したデリゲートが等しくないかどうかを判断します。

拡張メソッド

GetMethodInfo(Delegate)

指定したデリゲートによって表されるメソッドを表すオブジェクトを取得します。

適用対象

こちらもご覧ください