C#两个实体之间相同属性值的映射

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/xiong451823652/article/details/94718943

DTO:

  public class Person1
    {
        public int Id { set; get; } 

        public string Name { set; get; } 
        public string Sex { set; get; } 
    }

数据源:

public class Person
    {

        public int Id { set; get; } = 10;

        public string Name { set; get; } = "熊";
        public string Sex { set; get; } = "男";
    
    }

使用:

 var person = new Person();
            var persion1=B.Map<Person1, Person>(person);

工具类:

public class B
    {
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="R">目标实体</typeparam>
        /// <typeparam name="T">数据源实体</typeparam>
        /// <param name="model"></param>
        /// <returns></returns>
        public static R Map<R, T>(T model)
        {
            //动态实例化对象
            R result = Activator.CreateInstance<R>();
            foreach (PropertyInfo info in typeof(R).GetProperties())
            {
                //判断是否是相同属性
                PropertyInfo pro = typeof(T).GetProperty(info.Name);
                if (pro != null)
                    //赋值
                    info.SetValue(result, pro.GetValue(model));
            }
            return result;
        }
    }

猜你喜欢

转载自blog.csdn.net/xiong451823652/article/details/94718943