Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
public static class EventFactory
{
public static Event<T> Create<T>(Expression<Func<T>> eventExpr)
{
return new Event<T>(eventExpr);
}
}
public class Event<T>
{
public Event(Expression<Func<T>> eventExpr)
{
var memberExpr = eventExpr.Body as MemberExpression;
this.m_instance = memberExpr.Expression == null ? null :
Expression.Lambda<Func<object>>(memberExpr.Expression).Compile()();
var bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.InvokeMethod |
(this.m_instance == null ? BindingFlags.Static : BindingFlags.Instance);
var member = memberExpr.Member;
this.m_addMethod = member.DeclaringType.GetMethod("add_" + member.Name, bindingFlags);
this.m_removeMethod = member.DeclaringType.GetMethod("remove_" + member.Name, bindingFlags);
}
private object m_instance;
private MethodInfo m_addMethod;
private MethodInfo m_removeMethod;
public Event<T> AddHandler(T handler)
{
this.m_addMethod.Invoke(this.m_instance, new object[] { handler });
return this;
}
public Event<T> RemoveHandler(T handler)
{
this.m_removeMethod.Invoke(this.m_instance, new object[] { handler });
return this;
}
public static Event<T> operator +(Event<T> ev, T handler)
{
return ev.AddHandler(handler);
}
public static Event<T> operator -(Event<T> ev, T handler)
{
return ev.RemoveHandler(handler);
}
}
class Program
{
public event EventHandler Submit;
static void Main(string[] args)
{
Program p = new Program();
var ev = EventFactory.Create(() => p.Submit);
ev += (sender, eventArgs) => Console.WriteLine(sender);
p.Submit("Hello World", EventArgs.Empty);
Console.WriteLine("Press any key to exit...");
Console.ReadLine();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment