EntityExtend类

 

 

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
    {
    }
}

 

posted @ 2020-04-23 19:52  jacketlin  阅读(176)  评论(0编辑  收藏  举报