泛化委托代码 (C#)
我有两个非常相似的类,它们基本上做同样的事情。唯一的区别在于提供给每个类的实例的回调处理程序。回调处理程序不同,并且接受不同的参数。我想将这些类中的大部分代码概括为基类。关于如何智能地概括委托代码有什么想法吗?我使用 .NET 2.0
注意: 我阅读了 这个关于委托继承的非常有用的博客以及关于委托的协变和逆变的文章,但我仍然不知道如何在这里应用这些知识。
public class A
{
public delegate void AHandler(string param1, string param2);
public void AcceptHandler(string param3, AHandler handler);
public void InvokeHandler(string forParam1, string forParam2);
// the rest is same
}
public class B
{
public delegate void BHandler(int param1);
public void AcceptHandler(int param2, int param3, int param4, BHandler handler);
public void InvokeHandler(int forParam1);
// the rest is same
}
编辑:代码的“其余部分”完全相同,除了对具有不同签名的委托方法的调用之外。像这样的东西:
public void StartListening()
{
Timer timer = new Timer(CheckForChanges, null, 0, 1000);
}
private void CheckForChanges()
{
// pull changes, and pass different params to InvokeHandler()
}
I have two very similar classes that do essentially the same thing. The only difference is in a callback handler provided to an instance of each class. The callback handlers are different and they are accepted with different parameters. I would like to generalize most of the code from these classes into a base class. Any ideas on how to generalize the delegate code intelligently? I'm on .NET 2.0
Note: I read this very useful blog on inheritance with delegates and articles on covariance and contravariance with delegates, but I still don't see how that knowledge can be applied here.
public class A
{
public delegate void AHandler(string param1, string param2);
public void AcceptHandler(string param3, AHandler handler);
public void InvokeHandler(string forParam1, string forParam2);
// the rest is same
}
public class B
{
public delegate void BHandler(int param1);
public void AcceptHandler(int param2, int param3, int param4, BHandler handler);
public void InvokeHandler(int forParam1);
// the rest is same
}
EDIT: "the rest" of the code is exact same, except calls to the delegate methods that have different signatures. Something like this:
public void StartListening()
{
Timer timer = new Timer(CheckForChanges, null, 0, 1000);
}
private void CheckForChanges()
{
// pull changes, and pass different params to InvokeHandler()
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为什么不这样设置:
编辑:我已更新以包含您编辑的方法。
这样,您将在单个类中拥有相同的所有代码,然后各个类
A
和B
可以具有您需要的任何形式的方法。或者您是否正在寻找一种通用调用委托的方法,而不管哪个类?
IE。像这样的东西:
Why not set it up like this:
Edit: I've updated to include the methods from your edit.
This way, you'll have all your code that is the same in a single class, and then the individual classes
A
andB
can have whatever form of the methods you need.Or are you looking for a way to invoke the delegates generically irrespective of which class?
ie. Something like: