2016年2月16日 星期二

【C#】Auto assign(reflect) same name properties between different class obj

自動將 A 類別相同名稱的屬性值匯給 B類別

網路上有很多開源 API 可以做這件事,可是如果你像我一樣需要自己寫一個簡單的的話
  1. public static B CopyProperties<A, B>(A a, B b)
  2. {
  3. var typeOfA = a.GetType();
  4. var typeOfB = b.GetType();
  5.  
  6. // copy properties
  7. foreach (var propertyOfA in typeOfA.GetProperties())
  8. {
  9. try
  10. {
  11. var propertyOfB = typeOfB.GetProperty(propertyOfA.Name);
  12. if (propertyOfB != null)
  13. {
  14. if (propertyOfA.PropertyType.Namespace == "System")
  15. propertyOfB.SetValue(b, propertyOfA.GetValue(a));
  16. else
  17. {
  18. if (b is ICloneable)
  19. propertyOfB.SetValue(b, ((ICloneable)propertyOfA.GetValue(a)).Clone());
  20. else
  21. throw new Exception(string.Format(
  22. "Property {0} is customer class but didn't implement ICloneable.",
  23. propertyOfB.Name));
  24. }
  25. }
  26. else
  27. throw new Exception(string.Format(
  28. "Target class didn't have Property {0}.",
  29. propertyOfA.Name));
  30.  
  31. }
  32. catch (Exception ex)
  33. {
  34. string msg = ex.Message;
  35. }
  36. }
  37. return b;
  38. }

其中
  1. if (propertyOfA.PropertyType.Namespace == "System")
為判斷 prop 是否是基礎型別,是的話就直接賦予,不是的話則要實作 ICloneable 以深複製(未實作則不複製該 prop)。

範例: github

ref: reflectioncheck if implement spec interfacecheck if has spec methodcheck if has spec propcheck if its a system basic type(ex. int, char, bool, and so on).

沒有留言:

張貼留言