• C#如何获取实体类中的属性名和值
  • 发布于 2个月前
  • 574 热度
    0 评论
  • 北风吹
  • 0 粉丝 66 篇博客
  •   
数据模型定义
  public class User
    {
        public User()
        {
            student = new student();
        }
        public string name { get; set; }
        public string gender { get; set; }
        public int age { get; set; }

        public student student { get; set; }
    }
    public class student
    {
        public int ID { get; set; }
        public string  color { get; set; }
    }
这里定义了一个user类,分别是姓名、性别、和年龄,
类中又嵌套了一个学生类

数据初始化和打印
        static void Main(string[] args)
        {
            User u = new User();
            u.name = "zyr";
            u.gender = "男";

            u.student.ID = 1;
            u.student.color = "black";

            Console.WriteLine(getProperties(u));
            Console.ReadKey();
        }
这里在数据初始化赋值后在控制台打印输出,调用了getProperties这个方法,
  public static string getProperties<T>(T t)
        {
          
            if (t == null)
            {
                return tStr;
            }
            PropertyInfo[] properties = t.GetType().GetProperties();

            foreach (PropertyInfo item in properties)
            {
                string name = item.Name;
                object value = item.GetValue(t);
                if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String"))
                {
                    tStr += string.Format("{0}:{1},\n", name, value);
                }
                else if (item.PropertyType.Name.StartsWith("student"))
                {
                    getProperties(value);
                }
            }
            return tStr;
        }
getProperties在这里用来获取类中属性和值.

以上就是我在项目中获取实体类属性名和值的用法。简单又实用!
用户评论