namespace CommonHelper
{
    using System;

    public static class ObjExtend
    {
        /// <summary>
        /// 从目标对象中复制属性的值，执行浅表复制
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="t">复制目标</param>
        /// <param name="s">复制原</param>
        /// <returns></returns>
        public static T CopyFrom<T>(this T t,object s) where T : class {
            foreach(var p in s.GetType().GetProperties()) {
                if(p.CanRead) {
                    var tp = t.GetType().GetProperty(p.Name);
                    if(tp != null && tp.CanWrite && canConvert(p.PropertyType,tp.PropertyType)) {
                        tp.SetValue(t,p.GetValue(s));
                    }
                }
            }
            return t as T;
        }
        /// <summary>
        /// 判断一个类型是否可以转换为另一个类型
        /// </summary>
        /// <param name="source">原类型</param>
        /// <param name="target">目标类型</param>
        private static bool canConvert(Type source,Type target) {
            //引用类型判断
            if(target.IsAssignableFrom(source)) {
                return true;
            }
            //Nullable<>类型判断
            //值类型判断
            return false;
        }
    }
}