C# Events as parameter in a method
I want to use event itself in my method. Is it possible? Can "PlayWithEvent" method use "EventSource.Test" event as parameter?
public class EventSource
{
public event EventHandler Test;
}
class Program
{
static void Main(string[] args)
{
EventSource src = new EventSource ();
PlayWithEvent (src.Test);
}
static void PlayWithEvent (EventHandler e)
{
e (null, null);
}
}
I want a syntax something like that:
c开发者_如何学JAVAlass Program
{
static void Main(string[] args)
{
EventSource src = new EventSource ();
PlayWithEvent (src.Test);
}
static void PlayWithEvent (event e)
{
e += something;
}
}
Your code won't compile—you can only access the EventHandler
delegate for the event from within the same class as the event, and even then it would be null
unless you actually add an event handler to call.
It is not currently working because you marked
public event EventHandler Test;
as an event.
Remove the event tag and try again. It now works for me. The reason for this are the restrictions that C# has for events... But in your code, all you want is a delegate. Declare your class as:
public class EventSource
{
public EventHandler Test;
}
Note that I removed event:
public EventHandler Test;
You can't do it like that. You need to pass the actual class.
public class EventSource
{
public event EventHandler Test;
public void TriggerEvent()
{
Test(this, EventArgs.Empty);
}
}
class Program
{
static void Main(string[] args)
{
EventSource src = new EventSource ();
PlayWithEvent (src);
}
static void PlayWithEvent (EventSource e)
{
src.TriggerEvent();
}
}
You can do it in a more generic way by introducing an interface:
public interface IEventPublisher<T> where T : EventArgs
{
public void Publish(T args);
}
public class EventSource : IEventPublisher<EventArgs>
{
public event EventHandler Test;
public void Publish(EventArgs args)
{
Test(this, args);
}
}
class Program
{
static void Main(string[] args)
{
EventSource src = new EventSource ();
PlayWithEvent (src);
}
static void PlayWithEvent (IEventPublisher<EventArgs> publisher)
{
publisher.Publish(EventArgs.Empty);
}
}
Only the class that an event is defined on can raise the event. If you need other classes to be able to manipulate it, you'll have to use a regular delegate.
Note, however, that since Test
resolves to the underlying delegate when used within the scope of EventSource
(as opposed to the externally accessible event), EventSource
can pass it as a parameter to an external method.
精彩评论