现在需要EventArg类,我们有泛型

leo*_*ora 19 c# generics eventargs

使用泛型,是否有理由创建特定的派生EventArg类

现在看起来你可以通过通用实现轻松地使用它们.

我应该去看看我的所有示例并删除我的eventArg类(StringEventArgs,MyFooEventArgs等).

public class EventArgs<T> : EventArgs
{
    public EventArgs(T value)
    {
        m_value = value;
    }

    private T m_value;

    public T Value
    {
        get { return m_value; }
    }
}
Run Code Online (Sandbox Code Playgroud)

Bry*_*tts 37

您所描述的基本上是元组,用于特定目的的分组值.它们是函数式编程和支持中非常有用的构造.

缺点是它们的值没有命名,它们需要理解上下文.EventArgs就其性质而言,往往远离其相关背景.因此,元组式EventArgs对于消费者来说可能非常混乱.

假设我们有一个事件表明已经完成了一些除法,它带有分子,分母和结果:

public event EventHandler<EventArgs<double, double, double>> Divided;
Run Code Online (Sandbox Code Playgroud)

事件处理程序有一些含糊之处:

private void OnDivided(object sender, EventArgs<double, double, double> e)
{
    // I have to just "know" this - it is a convention

    var numerator = e.Value1;
    var denominator = e.Value2;
    var result = e.Value3;
}
Run Code Online (Sandbox Code Playgroud)

EventArgs代表事件会更清楚:

private void OnDivided(object sender, DividedEventArgs e)
{
    var numerator = e.Numerator;
    var denominator = e.Denominator;
    var result = e.Result;
}
Run Code Online (Sandbox Code Playgroud)

通用可重用EventArgs类以牺牲表达意图为代价来简化机制的开发.

  • 您可以使用通用事件args实现示例,以将您自己的类返回为:public class Division {double Num,double Denom,double Result},然后是EventHandler <EventArgs <Division >>. (2认同)