码迷,mamicode.com
首页 > 其他好文 > 详细

EntityExtend类

时间:2020-04-23 21:24:08      阅读:60      评论:0      收藏:0      [点我收藏+]

标签:dict   get   contains   EAP   type   from   spro   system   prope   

 

 

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApp4
{
    using System;
    using System.Collections.Generic;
    using System.Reflection;
    using System.Text;

    /// <summary>
    /// 扩展
    /// </summary>
    public static class EntityExtend
    {
        /// <summary>
        /// 拷贝
        /// </summary>
        /// <param name="entity">实体</param>
        /// <param name="fromEntity">来源实体</param>
        public static void CopyFrom(this IEntity entity, IEntity fromEntity)
        {
            var thisPros = entity.GetProperties();
            var fromPros = fromEntity.GetProperties();
            foreach (var key in thisPros.Keys)
            {
                if (fromPros.ContainsKey(key))
                {
                    var fromProperty = fromPros[key];
                    var thisProperty = thisPros[key];
                    if (thisProperty.CanWrite && fromProperty.CanRead && thisProperty.PropertyType == fromProperty.PropertyType)
                    {
                        thisProperty.SetValue(entity, fromProperty.GetValue(fromEntity));
                    }
                }
            }
        }

        /// <summary>
        /// 获取属性键值对
        /// </summary>
        /// <param name="entity">实体</param>
        /// <returns>键值对</returns>
        private static IDictionary<string, PropertyInfo> GetProperties(this IEntity entity)
        {
            var ret = new Dictionary<string, PropertyInfo>();

            PropertyInfo[] properties = entity.GetType().GetProperties();
            foreach (var p in properties)
            {
                ret.Add(p.Name.ToLower(), p);
            }

            return ret;
        }
    }
    public interface IEntity
    {
    }
}

 

EntityExtend类

标签:dict   get   contains   EAP   type   from   spro   system   prope   

原文地址:https://www.cnblogs.com/jacketlin/p/12469636.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!