EventInfo.AddEventHandler(Object, Delegate) EventInfo.AddEventHandler(Object, Delegate) EventInfo.AddEventHandler(Object, Delegate) EventInfo.AddEventHandler(Object, Delegate) Method

定義

イベント ソースにイベント ハンドラーを追加します。Adds an event handler to an event source.

public:
 virtual void AddEventHandler(System::Object ^ target, Delegate ^ handler);
public virtual void AddEventHandler (object target, Delegate handler);
abstract member AddEventHandler : obj * Delegate -> unit
override this.AddEventHandler : obj * Delegate -> unit
Public Overridable Sub AddEventHandler (target As Object, handler As Delegate)

パラメーター

target
Object Object Object Object

イベント ソース。The event source.

handler
Delegate Delegate Delegate Delegate

イベント ソースがイベントを発生させるたびに呼び出されるメソッドをカプセル化します。Encapsulates a method or methods to be invoked when the event is raised by the target.

実装

例外

イベントにパブリック add アクセサーがありません。The event does not have a public add accessor.

渡されたハンドラーは使用できません。The handler that was passed in cannot be used.

Windows ストア アプリ用 .NET またはポータブル クラス ライブラリでは、基本クラスの例外である MemberAccessException を代わりにキャッチします。In .NET for Windows Store apps or the Portable Class Library, catch the base class exception, MemberAccessException, instead.

呼び出し元には、このメンバーに対するアクセス許可がありません。The caller does not have access permission to the member.

Windows ストア アプリ用 .NET またはポータブル クラス ライブラリでは、Exception を代わりにキャッチします。In .NET for Windows Store apps or the Portable Class Library, catch Exception instead.

target パラメーターは null で、イベントは静的でありません。The target parameter is null and the event is not static.

- または --or- EventInfo はターゲットで宣言されていません。The EventInfo is not declared on the target.

次の例では、 System.Timers.Timerクラスのインスタンスを作成し、動的アセンブリを使用してイベントハンドラーを作成し、動的イベントハンドラーをフックします。The following example creates an instance of the System.Timers.Timer class, creates an event handler using a dynamic assembly, and hooks up the dynamic event handler. すべてのアクションは、遅延バインディングを使用して実行されます。All actions are performed using late binding.

インスタンスは型Objectの変数に格納され、にアクセスするすべてのTimerコードは遅延バインディングを実行します。 TimerThe Timer instance is stored in a variable of type Object, and all code that accesses the Timer does so late-bound. この例ではType.GetEvent 、メソッドを使用ElapsedしてイベントをEventHandlerType取得し、プロパティを使用してイベントのデリゲート型を取得します。The example uses the Type.GetEvent method to get the Elapsed event, and the EventHandlerType property to get the delegate type for the event.

この例ではMethodInfo 、デリゲートInvoke型のメソッドのを取得し、 MethodInfoインスタンスからデリゲートのシグネチャを取得します。The example gets a MethodInfo for the Invoke method of the delegate type and obtains the signature of the delegate from the MethodInfo instance. 次に、とHandlerいう名前の単一の型を含む1つのモジュールを持つ動的アセンブリを作成し、そのイベントを処理するという名前DynamicHandlerのメソッド (Shared Visual Basic 内のメソッド) をstatic型に渡します。The example then creates a dynamic assembly with one module containing a single type named Handler and gives the type a static method (Shared method in Visual Basic) named DynamicHandler that handles the event.

動的な型が作成された後、このMethodInfo例では、完成したメソッドのを取得し、それを使用してデリゲートインスタンスを作成します。After the dynamic type is created, the example gets a MethodInfo for the finished method and uses it to create a delegate instance. このインスタンスは、イベントをAddEventHandlerフックするためにメソッドに渡されます。This instance is passed to the AddEventHandler method to hook up the event. その後、プログラムはイベントの発生を許可するために一時停止します。The program then pauses to allow the event to be raised.

using System;
using System.Reflection;
using System.Reflection.Emit;

public class Example
{
    private static object timer;

    public static void Main()
    {
        // Get the Timer type.
        Type t = typeof(System.Timers.Timer);
        // Create an instance of the Timer type.
        timer = Activator.CreateInstance(t);

        // Use reflection to get the Elapsed event.
        EventInfo eInfo = t.GetEvent("Elapsed");

        // In order to create a method to handle the Elapsed event,
        // it is necessary to know the signature of the delegate 
        // used to raise the event. Reflection.Emit can then be
        // used to construct a dynamic class with a static method
        // that has the correct signature.
 
        // Get the event handler type of the Elapsed event. This is
        // a delegate type, so it has an Invoke method that has
        // the same signature as the delegate. The following code
        // creates an array of Type objects that represent the 
        // parameter types of the Invoke method.
        //
        Type handlerType = eInfo.EventHandlerType;
        MethodInfo invokeMethod = handlerType.GetMethod("Invoke");
        ParameterInfo[] parms = invokeMethod.GetParameters();
        Type[] parmTypes = new Type[parms.Length];
        for (int i = 0; i < parms.Length; i++)
        {
            parmTypes[i] = parms[i].ParameterType;
        }

        // Use Reflection.Emit to create a dynamic assembly that
        // will be run but not saved. An assembly must have at 
        // least one module, which in this case contains a single
        // type. The only purpose of this type is to contain the 
        // event handler method. (You can use also dynamic methods, 
        // which are simpler because there is no need to create an 
        // assembly, module, or type.)
        //
        AssemblyName aName = new AssemblyName();
        aName.Name = "DynamicTypes";
        AssemblyBuilder ab = AssemblyBuilder.DefineDynamicAssembly(aName, AssemblyBuilderAccess.Run);
        ModuleBuilder mb = ab.DefineDynamicModule(aName.Name);
        TypeBuilder tb = mb.DefineType("Handler", TypeAttributes.Class | TypeAttributes.Public);

        // Create the method that will handle the event. The name
        // is not important. The method is static, because there is
        // no reason to create an instance of the dynamic type.
        //
        // The parameter types and return type of the method are
        // the same as those of the delegate's Invoke method, 
        // captured earlier.
        MethodBuilder handler = tb.DefineMethod("DynamicHandler", 
            MethodAttributes.Public | MethodAttributes.Static, 
            invokeMethod.ReturnType, parmTypes);

        // Generate code to handle the event. In this case, the 
        // handler simply prints a text string to the console.
        //
        ILGenerator il = handler.GetILGenerator();
        il.EmitWriteLine("Timer's Elapsed event is raised.");
        il.Emit(OpCodes.Ret);

        // CreateType must be called before the Handler type can
        // be used. In order to create the delegate that will
        // handle the event, a MethodInfo from the finished type
        // is required.
        Type finished = tb.CreateType();
        MethodInfo eventHandler = finished.GetMethod("DynamicHandler");

        // Use the MethodInfo to create a delegate of the correct 
        // type, and call the AddEventHandler method to hook up 
        // the event.
        Delegate d = Delegate.CreateDelegate(handlerType, eventHandler);
        eInfo.AddEventHandler(timer, d);

        // Late-bound calls to the Interval and Enabled property 
        // are required to enable the timer with a one-second
        // interval.
        t.InvokeMember("Interval", BindingFlags.SetProperty, null, timer, new Object[] { 1000 });
        t.InvokeMember("Enabled", BindingFlags.SetProperty, null, timer, new Object[] { true });

        Console.WriteLine("Press the Enter key to end the program.");
        Console.ReadLine();
    }
}
/* This example produces output similar to the following:

Press the Enter key to end the program.
Timer's Elapsed event is raised.
Timer's Elapsed event is raised.
Timer's Elapsed event is raised.
*/

Imports System.Reflection
Imports System.Reflection.Emit

Public Class Example

    Private Shared timer As Object
    
    Public Shared Sub Main() 
        ' Get the Timer type.
        Dim t As Type = GetType(System.Timers.Timer)
        ' Create an instance of the Timer type.
        timer = Activator.CreateInstance(t)
        
        ' Use reflection to get the Elapsed event.
        Dim eInfo As EventInfo = t.GetEvent("Elapsed")
        
        ' In order to create a method to handle the Elapsed event,
        ' it is necessary to know the signature of the delegate 
        ' used to raise the event. Reflection.Emit can then be
        ' used to construct a dynamic class with a static method
        ' that has the correct signature.
        '
        ' Get the event handler type of the Elapsed event. This is
        ' a delegate type, so it has an Invoke method that has
        ' the same signature as the delegate. The following code
        ' creates an array of Type objects that represent the 
        ' parameter types of the Invoke method.
        '
        Dim handlerType As Type = eInfo.EventHandlerType
        Dim invokeMethod As MethodInfo = handlerType.GetMethod("Invoke")
        Dim parms As ParameterInfo() = invokeMethod.GetParameters()
        '
        ' Note that in Visual Basic you must dimension the array one
        ' unit smaller than the source array in order to get an array
        ' of the same size. This is because Visual Basic adds an extra
        ' element to every array, for ease of use.
        '
        Dim parmTypes(parms.Length - 1) As Type
        Dim i As Integer
        For i = 0 To parms.Length - 1
            parmTypes(i) = parms(i).ParameterType
        Next i
        
        ' Use Reflection.Emit to create a dynamic assembly that
        ' will be run but not saved. An assembly must have at 
        ' least one module, which in this case contains a single
        ' type. The only purpose of this type is to contain the 
        ' event handler method. (You can alsso use dynamic methods, 
        ' which are simpler because there is no need to create an 
        ' assembly, module, or type.)
        Dim aName As New AssemblyName()
        aName.Name = "DynamicTypes"
        Dim ab As AssemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(aName, AssemblyBuilderAccess.Run)
        Dim mb As ModuleBuilder = ab.DefineDynamicModule(aName.Name)
        Dim tb As TypeBuilder = mb.DefineType("Handler", TypeAttributes.Class Or TypeAttributes.Public)
        
        ' Create the method that will handle the event. The name
        ' is not important. The method is Shared ("static" in 
        ' reflection), because there is no reason to create an 
        ' instance of the dynamic type "Handler".
        '
        ' The parameter types and return type of the method are
        ' the same as those of the delegate's Invoke method, 
        ' captured earlier.
        Dim handler As MethodBuilder = tb.DefineMethod("DynamicHandler", MethodAttributes.Public Or MethodAttributes.Static, invokeMethod.ReturnType, parmTypes)
        
        ' Generate code to handle the event. In this case, the 
        ' handler simply prints a text string to the console.
        '
        Dim il As ILGenerator = handler.GetILGenerator()
        il.EmitWriteLine("Timer's Elapsed event is raised.")
        il.Emit(OpCodes.Ret)
        
        ' CreateType must be called before the Handler type can
        ' be used. In order to create the delegate that will
        ' handle the event, a MethodInfo from the finished type
        ' is required.
        Dim finished As Type = tb.CreateType()
        Dim eventHandler As MethodInfo = finished.GetMethod("DynamicHandler")
        
        ' Use the MethodInfo to create a delegate of the correct 
        ' type, and call the AddEventHandler method to hook up 
        ' the event.
        Dim d As [Delegate] = [Delegate].CreateDelegate(handlerType, eventHandler)
        eInfo.AddEventHandler(timer, d)
        
        ' Late-bound calls to the Interval and Enabled property 
        ' are required to enable the timer with a one-second
        ' interval.
        t.InvokeMember("Interval", BindingFlags.SetProperty, Nothing, timer, New [Object]() {1000})
        t.InvokeMember("Enabled", BindingFlags.SetProperty, Nothing, timer, New [Object]() {True})
        
        Console.WriteLine("Press the Enter key to end the program.")
        Console.ReadLine()
    
    End Sub 
End Class 
' This example produces output similar to the following:
'      Press the Enter key to end the program.
'      Timer's Elapsed event is raised.
'      Timer's Elapsed event is raised.
'      Timer's Elapsed event is raised.

注釈

このメソッドは、ターゲットオブジェクトのイベントを同期するデリゲートを追加しようとします。This method attempts to add a delegate to synchronize the event on the target object.

ターゲットパラメーターによってイベントが発生するたびに、そのハンドラーによってカプセル化されたメソッドまたはメソッドが呼び出されます。Each time the event is raised by the target parameter, the method or methods encapsulated by the handler are invoked.

プログラムが既にAddEventHandlerコンパイルされた後に型を読み込む場合は、メソッドを使用することができます。 C#これは、+ = 構文WithEventsまたHandlesは Visual Basic とキーワードを使用してイベントをフックすることができない場合に使用します。You might use the AddEventHandler method when you load a type after the program is already compiled, when it is not possible to use the C# += syntax or the Visual Basic WithEvents and Handles keywords to hook up the event.

セキュリティ

ReflectionPermission
などの機構をInvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[])使用して遅延バインディングが呼び出された場合。when invoked late-bound through mechanisms such as InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]). MemberAccess (関連する列挙体)Associated enumeration: MemberAccess.

適用対象

こちらもご覧ください