[フレーム]
Last Updated: February 25, 2016
·
10.98K
· to_pe

Generic EventArgs class

Sometimes you want a simple event handler in C# that will pass single value e.g. a string. The default EventHandler<T> type expects that the generic T type inherits EventArgs which requires that we create a new class that inherits EventArgs. For passing a simple string or a number, this is simply too much boilerplate code.

But we can create a generic EventArgs class, something that is missing in FCL and which will wrap our variable thus satisfying EventHandler<T>.

public class EventArgs<T> : EventArgs
{
 public T Value { get; private set; }

 public EventArgs(T val)
 {
 Value = val;
 }
}

You declare your event with the following syntax:

public event EventHandler<EventArgs<string>> StringReceivedEvent;

The following snippet demonstrates how to use it:

public void OnStringReceived()
{
 if (StringReceivedEvent != null)
 StringReceivedEvent(this, new EventArgs<string>(somestring));
}

// client code
StringReceivedEvent += (o, e) => Console.WriteLine(e.Value);

AltStyle によって変換されたページ (->オリジナル) /