C#通过反射获取对象字段和值

114 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

`static void Main(string[] args) { UserInfo userInfo = new UserInfo(); userInfo.ID = 1; userInfo.Name = "bailey"; userInfo.CreateDate = DateTime.Now; userInfo.Number = Convert.ToDecimal(456.6467);

        string values = string.Empty;
        foreach (System.Reflection.PropertyInfo p in userInfo.GetType().GetProperties())
        {
            if (p.PropertyType == typeof(string))
            {
                values += string.Format("{0}='{1}', ", p.Name, p.GetValue(userInfo));
            }
            if (p.PropertyType == typeof(int)|| p.PropertyType == typeof(uint))
            {
                values += string.Format("{0}={1},", p.Name, p.GetValue(userInfo));
            }
            if (p.PropertyType == typeof(DateTime))
            {
                values += string.Format("{0}='{1}', ", p.Name, p.GetValue(userInfo));
            }
            if (p.PropertyType == typeof(decimal) || p.PropertyType == typeof(double)|| p.PropertyType == typeof(float))
            {
                values += string.Format("{0}={1}, ", p.Name, p.GetValue(userInfo));
            }
           
            if (p.PropertyType == typeof(bool))
            {
                values += string.Format("{0}={1}, ", p.Name, p.GetValue(userInfo));
            }
            if (p.PropertyType == typeof(sbyte))
            {
                values += string.Format("{0}={1}, ", p.Name, p.GetValue(userInfo));
            }
            if (p.PropertyType == typeof(byte) || p.PropertyType == typeof(short) || p.PropertyType == typeof(ushort) )
            {
                values += string.Format("{0}={1}, ", p.Name, p.GetValue(userInfo));
            }
            if (p.PropertyType == typeof(long) || p.PropertyType == typeof(ulong))
            {
                values += string.Format("{0}={1}, ", p.Name, p.GetValue(userInfo));
            }

            // values +=string.Format( "{0}={1},", p.Name, p.GetValue(userInfo));
            // Console.WriteLine("Name:{0} Value:{1}", p.Name, p.GetValue(userInfo));
        }
        Console.WriteLine(values);
        Console.ReadLine();
    }`