Understanding Generics—Creating Generic Delegates
Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio
Creating Generic Delegates
Last but not least, .NET 2.0 does allow you to define generic delegate types. For example, assume you wish to define a delegate that can call any method returning void and receiving a single argument. If the argument in question may differ, you could model this using a type parameter. To illustrate, ponder the following code (notice the delegate targets are being registered using both "traditional" delegate syntax and method group conversion):
namespace GenericDelegate { // This generic delegate can call any method // returning void and taking a single parameter. public delegate void MyGenericDelegate<T>(T arg); class Program { static void Main(string[] args) { Console.WriteLine ("***** Generic Delegates *****\n"); // Register target with 'traditional' //delegate syntax. MyGenericDelegate<string> strTarget = new MyGenericDelegate<string>(StringTarget); strTarget("Some string data"); // Register target using method group conversion. MyGenericDelegate<int> intTarget = IntTarget; intTarget(9); Console.ReadLine(); } static void StringTarget(string arg) { Console.WriteLine("arg in uppercase is: {0}", arg.ToUpper()); } static void IntTarget(int arg) { Console.WriteLine("++arg is: {0}", ++arg); } } }
Notice that MyGenericDelegate<T> defines a single type parameter that represents the argument
to pass to the delegate target. When creating an instance of this type, you are required to specify the
value of the type parameter as well as the name of the method the delegate will invoke. Thus, if you
specified a string type, you send a string value to the target method:
// Create an instance of MyGenericDelegate<T> // with string as the type parameter. MyGenericDelegate<string> strTarget = new MyGenericDelegate<string>(StringTarget); strTarget("Some string data");
Given the format of the strTarget object, the StringTarget() method must now take a single
string as a parameter:
static void StringTarget(string arg) { Console.WriteLine("arg in uppercase is: {0}", arg.ToUpper()); }
|

