Reflection - Iterate object's properties recursively within my own assemblies (Vb.Net/3.5)

后端 未结 2 561
北荒
北荒 2021-01-28 01:27

I wonder if anyone can help me - I\'ve not done much with reflection but understand the basic principles.

What I\'m trying to do:

I\'m in the pr

2条回答
  •  無奈伤痛
    2021-01-28 02:06

    you extension version on c# to use on any object

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Reflection;
    
    namespace Extensions
    {
        public static class ObjectExtension
        {
            public static string ToStringProperties(this object o)
            {
                return o.ToStringProperties(0);
            }
        public static string ToStringProperties(this object o, int level)
        {
            StringBuilder sb = new StringBuilder();
            string spacer = new String(' ', 2 * level);
            if (level == 0) sb.Append(o.ToString());
            sb.Append(spacer);
            sb.Append("{\r\n");
            foreach (PropertyInfo pi in o.GetType().GetProperties())
            {
    
                if (pi.GetIndexParameters().Length == 0)
                {
                    sb.Append(spacer);
                    sb.Append("  ");
                    sb.Append(pi.Name);
                    sb.Append(" = ");
    
                    object propValue = pi.GetValue(o, null);
                    if (propValue == null)
                    {
                        sb.Append(" ");
                    } else {
                        if (IsMyOwnType(pi.PropertyType))
                        {
                            sb.Append("\r\n");
                            sb.Append(((object)propValue).ToStringProperties(level + 1));
                        } else{
                            sb.Append(propValue.ToString());
                        }
                    }
                    sb.Append("\r\n");
                }
            }
            sb.Append(spacer);
            sb.Append("}\r\n");
            return sb.ToString();
        }
        private static bool IsMyOwnType(Type t) 
    {
        return (t.Assembly == Assembly.GetExecutingAssembly());
    }
    }
    }
    

提交回复
热议问题