C# 实体转换

使用反射转换实体

csharp 复制代码
        //泛型+反射
        public static T ConvertModel<T, P>(P pModel)
        {
            T ret = System.Activator.CreateInstance<T>();

            List<PropertyInfo> p_pis = pModel.GetType().GetProperties().ToList();
            PropertyInfo[] t_pis = typeof(T).GetProperties();

            foreach (PropertyInfo pi in t_pis)
            {
                //可写入数据
                if (pi.CanWrite)
                {
                    //忽略大小写
                    var name = p_pis.Find(s => s.Name.ToLower() == pi.Name.ToLower());
                    if (name != null && pi.PropertyType.Name == name.PropertyType.Name)
                    {
                        pi.SetValue(ret, name.GetValue(pModel, null), null);
                    }

                }
            }

            return ret;
        }
相关推荐
Tony Bai1 天前
高并发后端:坚守 Go,还是拥抱 Rust?
开发语言·后端·golang·rust
wjs20241 天前
Swift 类型转换
开发语言
秃了也弱了。1 天前
python实现定时任务:schedule库、APScheduler库
开发语言·python
weixin_440730501 天前
java数组整理笔记
java·开发语言·笔记
Thera7771 天前
状态机(State Machine)详解:原理、优缺点与 C++ 实战示例
开发语言·c++
niucloud-admin1 天前
java服务端——controller控制器
java·开发语言
夏幻灵1 天前
JAVA基础:基本数据类型和引用数据类型
java·开发语言
cike_y1 天前
Spring-Bean的作用域&Bean的自动装配
java·开发语言·数据库·spring
十八度的天空1 天前
第01节 Python的基础语法
开发语言·python
我是唐青枫1 天前
深入理解 C#.NET Interlocked.Increment:原子操作的核心
c#·.net