網路上有很多開源 API 可以做這件事,可是如果你像我一樣需要自己寫一個簡單的的話
public static B CopyProperties<A, B>(A a, B b)
{
var typeOfA = a.GetType();
var typeOfB = b.GetType();
// copy properties
foreach (var propertyOfA in typeOfA.GetProperties())
{
try
{
var propertyOfB = typeOfB.GetProperty(propertyOfA.Name);
if (propertyOfB != null)
{
if (propertyOfA.PropertyType.Namespace == "System")
propertyOfB.SetValue(b, propertyOfA.GetValue(a));
else
{
if (b is ICloneable)
propertyOfB.SetValue(b, ((ICloneable)propertyOfA.GetValue(a)).Clone());
else
throw new Exception(string.Format(
"Property {0} is customer class but didn't implement ICloneable.",
propertyOfB.Name));
}
}
else
throw new Exception(string.Format(
"Target class didn't have Property {0}.",
propertyOfA.Name));
}
catch (Exception ex)
{
string msg = ex.Message;
}
}
return b;
}
其中
if (propertyOfA.PropertyType.Namespace == "System")為判斷 prop 是否是基礎型別,是的話就直接賦予,不是的話則要實作 ICloneable 以深複製(未實作則不複製該 prop)。
範例: github
ref: reflection、check if implement spec interface、 check if has spec method、check if has spec prop、check if its a system basic type(ex. int, char, bool, and so on).
沒有留言:
張貼留言