If you'd like a more generic solution, using Closures
next to the jbueno solution, here it is: / p>
using System;
public class Program
{
public static void Main()
{
EventHandler @event = EventHandlerHelper.Once((object sender, EventArgs e) =>
{
Console.WriteLine("Somente uma vez");
});
@event.Invoke(null, null);
@event.Invoke(null, null);
}
}
public static class Functional
{
public static Action<T1, T2> Once<T1, T2>(Action<T1, T2> action)
{
var executed = false;
return (T1 arg1, T2 arg2) => {
if (!executed)
{
action(arg1, arg2);
executed = true;
}
};
}
}
public static class EventHandlerHelper
{
public static EventHandler Once(Action<object, EventArgs> action)
{
return Functional.Once(action).Invoke;
}
}
To see it working, here is .