1. Delegate 实例方法当一个实例方法被赋值给委托对象的时候,这个委托对象不仅要保留着对方法的引用,还要保留方法所属实例的引用
System.Delegate Target属性代表这个实例
如果引用的是静态方法,那么Target属性为null
using System;
namespace senorDotnet
{
public delegate void ProgressReporter(int percentComplete);
class X
{
public void InstanceProgress(int percentComplete)
=>Console.WriteLine(percentComplete);
}
class Program
{
static void Main(string[] args)
{
X x = new X();
ProgressReporter p = x.InstanceProgress;
p(99);
Console.WriteLine("The Target is the same x. {0}" ,p.Target == x);
Console.WriteLine(p.Method);
}
}
}
输出:
using System;
namespace senorDotnet
{
public delegate void ProgressReporter(int percentComplete);
class X
{
public static void InstanceProgress(int percentComplete)
=>Console.WriteLine(percentComplete);
}
class Program
{
static void Main(string[] args)
{
// X x = new X();
ProgressReporter p = X.InstanceProgress;
p(99);
// System.Delegate Target属性代表当前这个实例
// 如果引用的是静态方法,那么Target的属性就是null
Console.WriteLine(p.Target == null);
Console.WriteLine(p.Method);
}
}
}
输出:



