c# 遍历属性

public class Program
    {
        static void Main(string[] args)
        {
            TestC c = new TestC();
            c.p = new Person();
            c.p.value = 14124;
            GetProperty(c);
            Console.ReadKey();
        }

        public static void GetProperty(Object o)
        {
            if(o==null)
            {
                return;
            }
            var properties = o.GetType().GetProperties();
            foreach (var item in properties)
            {
                if (!item.PropertyType.Equals(typeof(string))
                    && !item.PropertyType.Equals(typeof(int))
                    && !item.PropertyType.Equals(typeof(short))
                    && !item.PropertyType.Equals(typeof(long))
                    && !item.PropertyType.Equals(typeof(decimal))
                    )
                {

                    Console.WriteLine(item.PropertyType);
                    GetProperty(item.GetValue(o));
                }
                else
                {
                    Console.WriteLine("{0}:{1}", item.Name, item.GetValue(o, null));
                }
                
            }
        }
    }



    public class TestC
    {
        public Person p { get; set; }
    }

    public class Person
    {
        public string name { get; set; }
        public int value { get; set; }
    }

猜你喜欢

转载自www.cnblogs.com/lvjianwei/p/9238147.html