I've got this code (well, something similar).
private delegate void GenericCallback<T>(T Info);
private void DoWork()
{
System.Threading.Thread Worker = new System.Threading.Thread(
delegate()
{
TestMethod(TestMethodCallback<string>);
}
);
Worker.Start();
}
private void TestMethod(GenericCallback<string> Callback)
{
System.Threading.Thread.Sleep(1000);
if(Callback != null)
{
Callback("Complete");
}
}
private void TestMethod(GenericCallback<int> Callback)
{
System.Threading.Thread.Sleep(1000);
if(Callback != null)
{
Callback(25);
}
}
private void TestMethodCallback<T>(T Info)
{
MessageBox.Show(Info.ToString());
}
Which allows me to call different versions of TestMethod
based on the type of a parameter, while also allowing me to have a single callback method.
Is this bad form, or an accepted practice?
It looks like you might be looking for the Action delegate type. It's basically what you have here: a generic void-returning delegate type.
Such an established practice, that some of the work has been done for you. Action
in this case, and Func
should you return a value, are generic delegates, precisely like this. An advantage is, if I saw your signature:
private void TestMethod(GenericCallback<string> Callback)
I have to look up what GenericCallback<string>
is. If I saw:
private void TestMethod(Action<string> callback)
I already know.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With