在事件声明中正确使用泛型 [英] Correct usage of generics in event declaration

查看:70
本文介绍了在事件声明中正确使用泛型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可以传递的数据对象:

I have a data object which I pass around :

public class TimedResult<T>
{
    public ResultRequest Request { get; set; }
    public T Data { get; set; }
    public TimeSpan TimeTaken { get; set; }
}

在我的Manager课堂上,我完成了一些引发事件的工作:

In my Manager class I have some work done which raises an event :

public void Execute(ResultRequest request)
{
    var result = new TimedResult<DataTable>();
    // fill data object here
    OnResult(result);
}

我已经将 OnResult 方法设置为通用方法:

I have made the OnResult method generic :

protected virtual void OnResult<T>(TimedResult<T> result)
{
    if (Result != null)
        Result(this, result);
}

但是如何使事件声明具有通用性?

public event EventHandler<TimedResult<T>> Result; // red line under T

我应该怎么做?

推荐答案

事件声明不能是通用的.他们可以从声明类型中使用泛型类型参数,但不能声明自己的泛型参数.因此,只有在声明 Result 的类型具有 T (直接或通过外部类型)的情况下(即如果它是 SomeManager<; T> :

Event declarations cannot be (open) generic. They can use generic type parameters from the declaring type, but they cannot declare their own generic parameters. So what you want is only possible if the type that declares Result has a T (either directly, or via an outer-type), i.e. if this is SomeManager<T>:

class SomeManager<T> {
     public event EventHandler<TimedResult<T>> Result;
}

然后, T 是上面的任何内容;在 SomeManager< int> 中,它将是 EventHandler< TimedResult< int>> 等.

then the T is whatever it is from above; in SomeManager<int> it will be an EventHandler<TimedResult<int>> and so on.

这篇关于在事件声明中正确使用泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆