使用反射枚举指定类型的所有对象

时间:2013-12-11 03:11:18

标签: .net reflection

如何使用反射枚举进程中的所有对象(指定类型)?

2 个答案:

答案 0 :(得分:0)

解决方案是使用Microsoft.Diagnostics.Runtime库http://blogs.msdn.com/b/dotnet/archive/2013/05/01/net-crash-dump-and-live-process-inspection.aspx
例如:

    int pid = Process.GetProcessesByName("HelloWorld")[0].Id;
    using (DataTarget dataTarget = DataTarget.AttachToProcess(pid, 5000))
    {
        string dacLocation = dataTarget.ClrVersions[0].TryGetDacLocation();
        ClrRuntime runtime = dataTarget.CreateRuntime(dacLocation);

        ClrHeap heap = runtime.GetHeap();
        foreach (ulong obj in heap.EnumerateObjects())
        {
            ClrType type = heap.GetObjectType(obj);
            ulong size = type.GetSize(obj);
            Console.WriteLine("{0,12:X} {1,8:n0} {2}", obj, size, type.Name);
        }
    }

答案 1 :(得分:-1)

试试这个。

if (list is System.Collections.IEnumerable)
{                      
  foreach (object obj in (list as System.Collections.IEnumerable))
  {

  }    
 }    
}