Paradox Game Engine  v1.0.0 beta06
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Events Macros Pages
AnonymousEventHandler.cs
Go to the documentation of this file.
1 // Copyright (c) 2014 Silicon Studio Corp. (http://siliconstudio.co.jp)
2 // This file is distributed under GPL v3. See LICENSE.md for details.
3 using System;
4 using System.Linq;
5 using System.Reflection;
6 
7 namespace SiliconStudio.Presentation.Core
8 {
9  public class AnonymousEventHandler
10  {
11  protected Action Action;
12  private Delegate eventHandler;
13  private EventInfo eventInfo;
14  private object target;
15 
16  public static AnonymousEventHandler RegisterEventHandler(EventInfo eventInfo, object target, Action handler)
17  {
18  ParameterInfo[] parameterInfos = eventInfo.EventHandlerType.GetMethod("Invoke").GetParameters();
19 
20  if (parameterInfos.Length != 2)
21  throw new ArgumentException("The given event info must have exactly two parameters.");
22 
23  Type argumentType = parameterInfos.Skip(1).First().ParameterType;
24  Type type = typeof(AnonymousEventHandler<>).MakeGenericType(argumentType);
25 
26  MethodInfo method = type.GetMethod("Handler");
27  var anonymousHandler = (AnonymousEventHandler)Activator.CreateInstance(type);
28  anonymousHandler.Action = handler;
29  anonymousHandler.eventHandler = Delegate.CreateDelegate(eventInfo.EventHandlerType, anonymousHandler, method);
30  anonymousHandler.eventInfo = eventInfo;
31  anonymousHandler.target = target;
32  eventInfo.AddEventHandler(target, anonymousHandler.eventHandler);
33 
34  return anonymousHandler;
35  }
36 
37  public static void UnregisterEventHandler(AnonymousEventHandler handler)
38  {
39  handler.eventInfo.RemoveEventHandler(handler.target, handler.eventHandler);
40  }
41  }
42 
43  /// <summary>
44  /// This class allow to register an anonymous handler to an event using reflection.
45  /// </summary>
46  /// <typeparam name="TEventArgs">The type of <see cref="EventArgs"/> expected by the event.</typeparam>
47  /// <seealso cref="AnonymousEventHandler.RegisterEventHandler"/>
48  internal class AnonymousEventHandler<TEventArgs> : AnonymousEventHandler where TEventArgs : EventArgs
49  {
50  public void Handler(object sender, TEventArgs e)
51  {
52  Action();
53  }
54  }
55 }
static void UnregisterEventHandler(AnonymousEventHandler handler)
static AnonymousEventHandler RegisterEventHandler(EventInfo eventInfo, object target, Action handler)