實體對象間傳值克隆

        /// <summary>
        /// 複製克隆
        /// </summary>
        /// <typeparam name="TSource">源頭對象類型</typeparam>
        /// <typeparam name="TTarget">目標對象類型</typeparam>
        /// <param name="s">源頭對象</param>
        /// <param name="t">目標對象</param>
        /// <param name="str">過濾掉的字段名稱(如:ID;DateTime,UserCode類的字段)</param>
        private void CopyObject<TSource, TTarget>(TSource s, TTarget t, params string[] strArray)
            where TSource : new()
            where TTarget : new()
        {
            foreach (var p in t.GetType().GetProperties()) // 以目標表爲參照對象
            {
                var p1 = p;
                // 參數傳入的字段略過
                if (strArray.FirstOrDefault(str => str.ToUpper() == p.Name.ToUpper()) != null)
                {
                    continue;
                }
                var s1 = s.GetType().GetField(p1.Name);
                if (s1 != null)
                {
                    p1.SetValue(t, s1.GetValue(null), null);
                }
                else
                {
                    var s2 = s.GetType().GetProperty(p1.Name);
                    if (s2 == null) continue;
                    p1.SetValue(t, s2.GetValue(s, null), null);
                }
            }
        }
相關文章
相關標籤/搜索