c# 反射赋值扩展方法
- public static T ToModel<T>(this object source) where T : class, new()
- {
- var target = new T();
- if (source == null)
- return null;
- foreach (var property in target.GetType().GetProperties())
- {
- var sourceProterty = source.GetType().GetProperty(property.Name);
- if (sourceProterty == null)
- {
- continue;
- }
- var propertyValue = sourceProterty.GetValue(source, null);
- if (propertyValue != null)
- {
- //property.SetValue(target, i, null);
- target.GetType().InvokeMember(property.Name, BindingFlags.SetProperty, null, target, new object[] { propertyValue });
- }
- }
- foreach (var field in target.GetType().GetFields())
- {
- var fieldValue = source.GetType().GetField(field.Name).GetValue(source);
- if (fieldValue != null)
- {
- target.GetType().InvokeMember(field.Name, BindingFlags.SetField, null, target, new object[] { fieldValue });
- }
- }
- return target;
- }