经过用什么类型的方法来声明为委托,能够分为两类:函数
1. 委托静态方法:把一个静态方法给委托测试
2. 委托实例方法:把一个实例对象的成员方法给委托this
(这两个名字是博主取的,可能不是很专业只是为了好区分)spa
委托是将函数指针和实例对象打包在一块儿的类,它有两个重要的成员,一个用来保存实例对象,一个用来保存函数的指针。从源码中咱们能够查看System.Delegate,以下:指针
1. 将会调用方法所在的对象code
// _target is the object we will invoke on [System.Security.SecurityCritical] internal Object _target;
2. 将会调用的方法指针对象
// _methodPtr is a pointer to the method we will invoke // It could be a small thunk if this is a static or UM call [System.Security.SecurityCritical] internal IntPtr _methodPtr;
另外,咱们查看System.Delegate的属性,咱们能够看到一个属性 Targetblog
public Object Target { get { return GetTarget(); } }
来看一下这个 GetTarget() 方法的功能rem
[System.Security.SecuritySafeCritical] internal virtual Object GetTarget() { return (_methodPtrAux.IsNull()) ? _target : null; }
能够看到这边有一个字段 _methodPtrAux,这是一个IntPtr类型的指针,能够看到注释能够看出,当把一个静态方法给委托的时候,将会返回一个 null,若是是一个实例方法的时候,将会返回当前方法所在的实例对象(this)get
// In the case of a static method passed to a delegate, this field stores // whatever _methodPtr would have stored: and _methodPtr points to a // small thunk which removes the "this" pointer before going on // to _methodPtrAux. [System.Security.SecurityCritical] internal IntPtr _methodPtrAux;
测试类 Test.cs:
public class Test { /// <summary> /// 实例方法 /// </summary> public void ShowHelloWorld1() { Console.WriteLine("Hello World! -- 1"); } /// <summary> /// 静态方法 /// </summary> public static void ShowHelloWorld2() { Console.WriteLine("Hello World! -- 2"); } }
委托声明:
public delegate void ShowHelloWorldMethod();
上端测试代码:
//声明测试对象 Test test = new Test(); //构造实例方法的委托 ShowHelloWorldMethod del = test.ShowHelloWorld1; //判断一下Target是否是指向方法所在的对象 Console.WriteLine(del.Target is Test);//True //调用一下 ((Test)del.Target).ShowHelloWorld1();//Hello World! -- 1 //构造静态方法的委托 ShowHelloWorldMethod del2 = Test.ShowHelloWorld2; //判断一下Target是否是null Console.WriteLine(del2.Target == null);//true
测试结果符合咱们的预期:
若是委托的Target属性为null说明是静态方法的委托,若是委托的Target属性不为null说明是实例方法的委托。