打印使用C#和反思完整的对象图 [英] Printing full object graph using C# and reflection

查看:104
本文介绍了打印使用C#和反思完整的对象图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个COMPEX对象

I have a compex object

class A
{
 int Field1;
 int field2;
 property ClassB ClassB;
 property classC classC;
 etc etc....

}



我想使用反射来打印完整的对象图。任何一个优秀的代码在那里?

I want to print the complete object graph using reflection. Any good code out there?

推荐答案

我做了一些几年前调试的目的。它是打印所有属性和子对象的递归函数。您打印的方式是由你。只要把你想要的代码在打印方法。这不是防弹,但它工作得很好:

I did something for debugging purpose some years ago. It's a recursive function that print all properties and sub object. The way you print is up to you. Just put the code you want in the print method. It's not "bullet proof" but it works pretty well :

private static void displayObject(object myObject, bool displaySubObject, Type objectType)
{
  print(objectType.FullName);
  if (myObject == null) 
  {
      print(STR_Null);
  }
  else 
  {
    //check for collection
    if (objectType.GetInterface("IEnumerable") != null) 
    {
      int itemNb = 0;
      foreach (object item in (IEnumerable)myObject) 
      {
        displayObject(item, displaySubObject, item.GetType);
        itemNb += 1;
      }
    }
    else 
    {
      ArrayList al = new ArrayList();
      Reflection.PropertyInfo pi = default(Reflection.PropertyInfo);
      Reflection.MemberInfo[] members = objectType.GetMembers();
      foreach (Reflection.MemberInfo mi in objectType.GetMembers()) 
      {
        if ((mi.MemberType & Reflection.MemberTypes.Constructor) != 0){//ignore constructor}
        else if (object.ReferenceEquals(mi.DeclaringType, typeof(object))) {//ignore inherited}
        else if (!al.Contains(mi.Name) & (mi.MemberType & Reflection.MemberTypes.Property) != 0) 
        {
          al.Add(mi.Name);
          pi = (Reflection.PropertyInfo)mi;
          if (!(displaySubObject) || (pi.PropertyType.IsValueType || pi.PropertyType.Equals(typeof(string)))) 
          {
            print(pi, myObject);
          }
          else 
          {
            //display sub objects
            displayObject(pi.GetValue(myObject, null), displaySubObject, i.PropertyType);
          }
        }
      }
    }
  }
}

希望它能帮助

这篇关于打印使用C#和反思完整的对象图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆