我试图创建一个事件委托,其中的参数是强类型的,以匹配当前类,如下所示:
public class HPCRequest
{
public delegate void RequestCompleteHandler(HPCRequest request);
public event RequestCompleteHandler RequestComplete;
问题是这个类的点是要被继承的,我真正想要的是所有继承类都有“requestComplete”事件,在这个事件中为该类键入委托:
public class HPCGetConfig : HPCRequest
{
//I want this class to effectively inherit something like this:
//public delegate void RequestCompleteHandler(HPCGetConfig request);
这是因为目前,当我有一个处理“requestComplete”事件的函数时,我必须执行以下操作:
myGetConfigRequest.RequestComplete += new HPCRequest.RequestCompleteHandler(HPCGetExpectedLosses_RequestComplete);
void HPCGetConfig_RequestComplete(HPCRequest request)
{
HPCGetConfig thisRequest = request as HPCGetConfig;
//This should be strongly typed in the first place.
但我想做这样的事:
request.RequestComplete += new HPCGetConfig.RequestCompleteHandler(HPCGetConfig_RequestComplete);
request.SendRequestAsync();
}
void HPCGetConfig_RequestComplete(HPCGetConfig request)
{
request.RequestComplete -= HPCGetConfig_RequestComplete;
尝试
我试过这个:
public delegate void RequestCompleteHandler<T>(T request) where T : HPCRequest;
public event RequestCompleteHandler<T> RequestComplete;
但是,当我试图使用
RequestComplete(this);
从基类内调用事件时,会出现编译时错误:“delegate”requestCompleteHandler“有一些无效参数。无论我是否通过以下步骤将整个
HPCRequest
类设置为HPCRequest<T>
,都会发生这种情况:public class HPCRequest<T> where T : HPCRequest<T>
{
public delegate void RequestCompleteHandler<T>(T request);
public event RequestCompleteHandler<T> RequestComplete;
public class HPCGetConfig : HPCRequest<HPCGetConfig> { ...
当我试图调用事件时,也会出现同样的错误:
RequestComplete(this);
_
我还尝试了创建委托和事件并覆盖它们的所有形式,例如:
public class HPCRequest
{
public delegate void RequestCompleteHandler(HPCRequest request);
public virtual event RequestCompleteHandler RequestComplete;
public sealed class HPCGetConfig : HPCRequest
{
public delegate void RequestCompleteHandler(HPCGetConfig request);
public override event RequestCompleteHandler RequestComplete;
但这会给我一个编译时错误,因为我不能用另一个委托类型重写requestComplete事件。
还有其他想法吗?
编辑
模板化整个hpcrequest类不是一个选项,经过一次非常彻底的尝试,我发现它只是破坏了使用hpcrequest类型作为任何请求类型占位符的每次尝试。如果这个解决方案要工作,则类
HPCRequest
必须能够在不指定类型参数的情况下被实例化和继承。我需要一个不需要模板化的解决方案。为了确保每个人都确切知道我是如何使用它的,我将一些示例代码粘贴到了PasteBin中,这样您就可以尝试在不破坏任何东西的情况下使此事件模板化工作的方法。在这里:http://pastebin.com/bbEYgLj1
最佳答案
你可以尝试什么:
public abstract class HPCRequest<T> where T : HPCRequest<T>
{
public delegate void RequestCompleteHandler(T request);
public event RequestCompleteHandler RequestComplete;
protected void RaiseRequestComplete(T request)
{
if (RequestComplete != null)
{
RequestComplete(request);
}
}
}
public class Foo : HPCRequest<Foo>
{
public void Bar()
{
RaiseRequestComplete(this);
}
}
public class Example
{
public static void Test()
{
var request = new Foo();
request.RequestComplete += RequestComplete;
}
static void RequestComplete(Foo request)
{
// It's a Foo!
}
}
这个自引用的泛型约束允许你想要的我认为。我添加了
protected RaiseRequestCompleted
以便您仍然可以从继承自hcprequest的类引发事件。否则,只允许HCPRequest
这样做。更新:我更新了代码以传递
this
,并添加了与所需结果匹配的示例代码。