1. 程式人生 > 實用技巧 >c# 反射迴圈給實體賦值

c# 反射迴圈給實體賦值

using System;
using System.Data.Objects.DataClasses;
using System.Reflection;
        static public void AutoMapping<S, T>(S s, T t)
        {
            PropertyInfo[] pps = s.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
            Type target = t.GetType();

            
foreach (var pp in pps) { PropertyInfo targetPP = target.GetProperty(pp.Name); object value = pp.GetValue(s, null); if (targetPP != null && value != null) { targetPP.SetValue(t, value, null); } } }
static public void CopyEFObject<S, T>(S s, T t) { PropertyInfo[] pps = s.GetType().GetProperties(); Type target = t.GetType(); foreach (var pp in pps) { PropertyInfo targetPP = target.GetProperty(pp.Name);
if (targetPP.IsDefined(typeof(EdmScalarPropertyAttribute))) { object value = pp.GetValue(s, null); if (targetPP != null && value != null) { targetPP.SetValue(t, value, null); } } } } CopyEFObject<Info, Info>(creditInfo, copyCredit); // 反射迴圈給實體賦值 var list = new List<Abnormal>(); sourceList.ForEach(row => { var entity = new Abnormal(); AutoMapping(row, entity); list.Add(entity); });