C#利用反射复制实体类

来源:互联网 发布:php网页跳转代码 编辑:程序博客网 时间:2024/06/06 02:02
public static void copyDataFromSourceToTarget<TSource, TTarget>(TSource s, TTarget t, string[] reqItems = null, bool create = false)
            where TSource : new()
            where TTarget : new()
        {
            foreach (var p in t.GetType().GetProperties()) // 以目标表为参照对象
            {
                // 复制到本地变量
                var p1 = p;
                if (reqItems != null && reqItems.All(w => w != p1.Name)) 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);
                }
            }
        }
0 0
原创粉丝点击