利用反射访问任意实体类

如题。

可以为以后统一的实体类操作做准备。

以下代码.net5调试通过。

实体类Person:

using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel.DataAnnotations;

namespace ConsoleApp1
{
    public class Person
    {
        [Key]
        [Display(Name = "姓名")]
        public string Xm { get; set; }
        [Display(Name = "年龄")]
        public int Nl { get; set; }
        public string Xb { get; set; }
        public Person(string _xm,int _nl,string _xb)
        {
            Xm = _xm;
            Nl = _nl;
            Xb = _xb;
        }
    }
}

主类(把main改个insert啥的就接近能用了):

using System;
using System.Linq;
using System.ComponentModel.DataAnnotations;
using System.Reflection;
using System.Collections.Generic;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Person p = new("张三", 20, "");
            PropertyInfo[] ps=getProperties(p);

            //获得主键和值
            var keyword= getKeyandValue(p,ps);

            //如果需要获得剩下(除主键外)的内容,则执行这一句
            //ps = ps.Where(p => p.ToString() != keyword.k.ToString()).ToArray();

            //获得所有属性和值
            var others = getAll(p,ps);

            //显示结果
            Console.WriteLine(keyword.k.ToString()+","+ keyword.v);
            Console.WriteLine("---------------------");
            foreach (var item in others)
            {
                Console.WriteLine(item.k + "," + item.v);
            }
        }
        static PropertyInfo[] getProperties(dynamic x)
        {
            return ((Type)(x.GetType())).GetProperties();
        }
        static (PropertyInfo k,string v) getKeyandValue(dynamic x,PropertyInfo[] ps)
        {
            var p = ps.Where(p => p.GetCustomAttributes(typeof(KeyAttribute), false).Length > 0).FirstOrDefault();
            return (p,p.GetValue(x).ToString());
        }
        static IEnumerable<(string k,string v)> getAll(dynamic x,PropertyInfo[] ps)
        {
            foreach (var item in ps)
            {
                yield return (item.ToString(), item.GetValue(x).ToString());
            }
        }
    }
}
原文地址:https://www.cnblogs.com/wanjinliu/p/14013408.html