Advanced C# - Instance Method Targets
(Page 3 of 4 )
When a delegate instance is assigned to an instance method, the delegate instance must maintain a reference not only to the method, but also to the instance of that method. The System.Delegate class’s Targetproperty represents this instance (and will be null for a delegate referencing a static method). For example:
public delegate void ProgressReporter (int percentComplete);
class Test
{
static void Main() {new Test();}
Test ()
{
ProgressReporter p = InstanceProgress;
p(99); // 99
Console.WriteLine (p.Target == this); // True
Console.WriteLine (p.Method); // Void InstanceProgress(Int32)
}
void InstanceProgress (int percentComplete)
{
Console.WriteLine(percentComplete);
}
}
Generic Delegate Types A delegate type may contain generic type parameters. For example:
public delegate T Transformer<T> (T arg);
With this definition, we can write a generalizedTransformutility method that works on any type:
public class Util
{
public static void Transform<T> (T[] values, Transformer<T> t)
{
for (int i = 0; i < values.Length; i++)
values[i] = t(values[i]);
}
}
class Test
{
static void Main()
{
int[] values = new int[] {1, 2, 3};
Util.Transform(values, Square); //
dynamically hook in Square
foreach (int i in values)
Console.Write (i + " "); // 1 4 9
}
static int Square (int x) { return x * x; }
}
Next: Delegates Versus Interfaces >>
More C# Articles
More By O'Reilly Media
|
This article is excerpted from chapter four of C# 3.0 in a Nutshell, Third Edition, A Desktop Quick Reference, written by Joseph Albahari and Ben Albahari (O'Reilly; ISBN: 0596527578). Check it out today at your favorite bookstore. Buy this book now.
|
|