分类目录

链接

2016年 7月
 123
45678910
11121314151617
18192021222324
25262728293031

近期文章

热门标签

新人福利,免费薅羊毛

现在位置:    首页 > .NET > 正文
c# 反射赋值扩展方法
.NET 暂无评论 阅读(1,375)
  1. public static T ToModel<T>(this object source) where T : class, new()
  2. {
  3. var target = new T();
  4. if (source == null)
  5. return null;
  6. foreach (var property in target.GetType().GetProperties())
  7. {
  8. var sourceProterty = source.GetType().GetProperty(property.Name);
  9. if (sourceProterty == null)
  10. {
  11. continue;
  12. }
  13.  
  14. var propertyValue = sourceProterty.GetValue(source, null);
  15.  
  16. if (propertyValue != null)
  17. {
  18.  
  19. //property.SetValue(target, i, null);
  20. target.GetType().InvokeMember(property.Name, BindingFlags.SetProperty, null, target, new object[] { propertyValue });
  21. }
  22.  
  23. }
  24.  
  25. foreach (var field in target.GetType().GetFields())
  26. {
  27. var fieldValue = source.GetType().GetField(field.Name).GetValue(source);
  28. if (fieldValue != null)
  29. {
  30. target.GetType().InvokeMember(field.Name, BindingFlags.SetField, null, target, new object[] { fieldValue });
  31. }
  32. }
  33.  
  34. return target;
  35. }

============ 欢迎各位老板打赏~ ===========

本文版权归Bruce's Blog所有,转载引用请完整注明以下信息:
本文作者:Bruce
本文地址:c# 反射赋值扩展方法 | Bruce's Blog

发表评论

留言无头像?