技术开发 频道

.NET面面观——探索.Net中的委托

  我们来自己动手,分析一下上面的结论是否正确。

  _target和_methodPtr真的如上面所说的么?何不自己动手看看。

  建立一个Console类型的工程,在项目属性的“调试(Debug)”选项卡里选中“允许非托管代码调试(Enable unmanaged code debuging)”。

namespace Yuyijq.DotNet.Chapter2  
{  
    
public delegate void MyDelegate(int para);  
    
public class TestDelegate  
     {  
        
public void Test(int para)  
         {  
             Console.WriteLine(
"Test Delegate");  
         }  
        
public void CallByDelegate()  
         {  
             MyDelegate myDelegate
= new MyDelegate(this.Test);  
             myDelegate(
5);  
         }  
    
        
static void Main()  
         {  
             TestDelegate test
= new TestDelegate();  
             test.CallByDelegate();  
         }  
     }  
}

  上面是作为实验的代码。

  在CallByDelegate方法的第二行设置断点

  F5执行,命中断电后,在Visual Studio的立即窗口(Immediate Window)里输入如下命令(菜单栏->调试(Debug)->立即窗口(Immediate)):

  //.load sos.dll用于加载SOS.dll扩展

  .load sos.dll

  extension C:\Windows\Microsoft.NET\Framework\v2.0.50727\sos.dll loaded

  //Dump Stack Objects的缩写,输出栈中的所有对象

  //该命令的输出有三列,第二列Object就是该对象在内存中的地址

  !dso

  PDB symbol for mscorwks.dll not loaded

  OS Thread Id: 0x1588 (5512)

  ESP/REG Object Name

  0037ec10 019928a4 Yuyijq.DotNet.Chapter2.TestDelegate

  0037ed50 019928a4 Yuyijq.DotNet.Chapter2.TestDelegate

  0037ed5c 019928b0 Yuyijq.DotNet.Chapter2.MyDelegate

  0037ed60 019928b0 Yuyijq.DotNet.Chapter2.MyDelegate

  0037ef94 019928b0 Yuyijq.DotNet.Chapter2.MyDelegate

  0037ef98 019928b0 Yuyijq.DotNet.Chapter2.MyDelegate

  0037ef9c 019928a4 Yuyijq.DotNet.Chapter2.TestDelegate

  0037efe0 019928a4 Yuyijq.DotNet.Chapter2.TestDelegate

  0037efe4 019928a4 Yuyijq.DotNet.Chapter2.TestDelegate

  //do命令为Dump Objects缩写,参数为对象地址,输出该对象的一些信息

  !do 019928b0

  Name: Yuyijq.DotNet.Chapter2.MyDelegate

  MethodTable: 00263100

  EEClass: 002617e8

  Size: 32(0x20) bytes

  (E:\Study\Demo\Demo\bin\Debug\Demo.exe)

  //该对象的一些字段

  Fields:

  MT Field Offset Type VT Attr Value Name

  704b84dc 40000ff 4 System.Object 0 instance 019928a4 _target

  704bd0ac 4000100 8 ...ection.MethodBase 0 instance 00000000 _methodBase

  704bb188 4000101 c System.IntPtr 1 instance 0026C018 _methodPtr

  704bb188 4000102 10 System.IntPtr 1 instance 00000000 _methodPtrAux

  704b84dc 400010c 14 System.Object 0 instance 00000000 _invocationList

  704bb188 400010d 18 System.IntPtr 1 instance 00000000 _invocationCount

  在最后Fields一部分,我们看到了_target喝_methodPtr,_target的值为019928a4,看看上面!dso命令的输出,这个不就是Yuyijq.DotNet.Chapter2.TestDelegate实例的内存地址么。

0
相关文章