問題
使用 泛型複製物件屬性
解決方法
public static class ObjectExt
{
public static void CopyTo(this T1 obj, ref T2 otherObject)
where T1 : class
where T2 : class
{
PropertyInfo[] destFields = otherObject.GetType().GetProperties(
BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetProperty);
PropertyInfo[] srcFields = obj.GetType().GetProperties(
BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty);
foreach (var property in srcFields)
{
var dest = destFields.FirstOrDefault(x => x.Name == property.Name);
if (dest != null && dest.CanWrite)
dest.SetValue(otherObject, property.GetValue(obj, null), null);
}
}
}
沒有留言:
張貼留言