C# 不一樣類型對象同名屬性賦值

/// <summary>
        /// 不一樣類型對象同名屬性賦值
        /// </summary>
        /// <typeparam name="S">源類型</typeparam>
        /// <typeparam name="T">目標類型</typeparam>
        /// <param name="s">源對象</param>
        /// <param name="t">目標對象</param>
        public static void AutoMapping<S, T>(S s, T t)
        {
            PropertyInfo[] pps = GetPropertyInfos(s.GetType());
            Type target = t.GetType();

            foreach (var pp in pps)
            {
                try
                {
                    PropertyInfo targetPP = target.GetProperty(pp.Name);
                    object value = pp.GetValue(s, null);

                    if (targetPP != null && value != null)
                    {
                        targetPP.SetValue(t, value, null);
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
相關文章
相關標籤/搜索