Delegate Code Summarization (C #)

I have two very similar classes that do essentially the same thing. The only difference is the callback handler provided to the instance of each class. Callback handlers are different, and they are accepted with different parameters. I would like to generalize most of the code from these classes to a base class. Any ideas on how to reasonably summarize the delegate code? 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 this 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 exactly the same, except for calls to delegate methods that have different signatures. Something like that:

 public void StartListening() { Timer timer = new Timer(CheckForChanges, null, 0, 1000); } private void CheckForChanges() { // pull changes, and pass different params to InvokeHandler() } 
+4
source share
1 answer

Why not configure it like this:
Change I updated to include methods from your edit.

 public abstract class AbstractBase { // "the rest" public void StartListening() { Timer timer = new Timer(CheckForChanges, null, 0, 1000); } protected abstract void CheckForChanges(); } public class A : AbstractBase { public delegate void AHandler(string param1, string param2); public void AcceptHandler(string param3, AHandler handler); public void InvokeHandler(string forParam1, string forParam2); protected override void CheckForChanges() { //Do stuff for this version of the class } } public class B : AbstractBase { public delegate void BHandler(int param1); public void AcceptHandler(int param2, int param3, int param4, BHandler handler); public void InvokeHandler(int forParam1); protected override void CheckForChanges() { //Do stuff for this version of the class } } 

This way, you will have all your code that will be the same in the same class, and then the separate classes A and B can have any form of methods that you need.

Or are you looking for a way to call delegates in general, no matter which class?

T. Something like:

 AbstractBase ab = new A(); ab.InvokeDelegate(); 
+5
source

All Articles