I have a small concern about generic delegates in C#. Here's the context:
I created 2 classes:
- GenericCallbacks: By default a method pointer and the call when asked.
- TestDelegate: It creates GenericCallbacks and methods of test attached to delegates.
Here is the complete code compiled, I will issue the following:
GenericCallbacks:
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestGenericDelegate
{
class GenericCallbacks
{
private Delegate action;
private int x;
private int y;
public delegate void Callback();
public delegate void Callback2(int x, int y);
/*
* [...]
* Many delegate prototyping different
* Not very clean..
*/
public GenericCallbacks(Delegate Action)
{
this.action = Action;
this.x = this.y = 0;
}
// public GenericCallbacks(Callback2 Action)
// {
// this.action = Action;
// this.x = this.y = 5;
// }
public void Invoke()
{
/* After various operations on x and y means I know what cast */
if (this.x != 0 && this.y != 0)
{
((Callback2)action).Invoke(x, y);
}
else
{
((Callback)action).Invoke();
}
}
}
}
TestDelegate :
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestGenericDelegate
{
class TestDelegate
{
public void Method1()
{
Console.WriteLine("Method 1." );
return;
}
public void Method2(int x, int y)
{
Console.WriteLine("Method 2 : {0}, {1}.", x, y);
return;
}
public TestDelegate()
{
GenericCallbacks unitTest = new GenericCallbacks(Method1);
GenericCallbacks unitTest2 = new GenericCallbacks(Method2);
unitTest.Invoke();
unitTest2.Invoke();
}
}
}
The main test:
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestGenericDelegate
{
class Program
{
static void Main(string[] args)
{
TestDelegate testDelegate = new TestDelegate();
Console.ReadKey(true);
}
}
}
The problem is as follows:
How to avoid creating so many constructors of delegate type in the class GenericCallbacks?
In the example I only have 2, but in the real program that asks me worry I have about 10, knowing that I have 1 overload for each type of delegates which gives 20 overload for the same how to add!
In my case, even if it's ugly, it might work, but I dare not imagine that the developer is left with 250 possible prototype for its delegates.
I tried to make the constructor a type System.Delegate but it is not working.
I'm looking for a generic type that can contain a pointer to method but I found none.
Bookmarks