当一个类的实例的方法被赋给一个委托对象时,在上下文中不仅要维护这个方法,还要维护这个方法所在的实例。System.Delegate 类的Target属性指向的就是这个实例。举个例子:
class Program {
static void Main(string[] args) {
X x = new X();
ProgressReporter p = x.InstanceProgress;
p(1);
Console.WriteLine(p.Target == x); // True
Console.WriteLine(p.Method); // Void InstanceProgress(Int32)
}
static void WriteProgressToConsole(int percentComplete) {
Console.WriteLine(percentComplete+"%");
}
static void WriteProgressToFile(int percentComplete) {
System.IO.File.AppendAllText("progress.txt", percentComplete + "%");
}
}
class X {
public void InstanceProgress(int percentComplete) {
// do something
}
}
但对于静态方法,System.Delegate 类的Target属性是Null,所以将静态方法赋值给委托时性能更优。