| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103 |
- // ***********************************************************************
- // <summary>
- //对象COPY/初始化帮助,通常是防止从视图中传过来的对象属性为空,这其赋初始值
- //</summary>
- // ***********************************************************************
- using System;
- using System.Reflection;
- namespace CommonTool
- {
- public static class ObjectHelper
- {
- public static T CopyTo<T>(this object source) where T:class, new()
- {
- var result = SetDefault(new T()) as T ?? new T();
- source.CopyTo(result);
- return result;
- }
-
- public static void CopyTo<T>(this object source, T target)
- where T : class,new()
- {
- if (source == null)
- return;
- if (target == null)
- {
- target = new T();
- }
- foreach (var property in target.GetType().GetProperties())
- {
- var propertyValue = source.GetType().GetProperty(property.Name).GetValue(source, null);
- if (propertyValue != null)
- {
- if (propertyValue.GetType().IsClass)
- {
- //EntityFactory.CreateEntity<> ();
- }
- target.GetType().InvokeMember(property.Name, BindingFlags.SetProperty, null, target, new[] { 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[] { fieldValue });
- }
- }
- }
- private static object SetDefault(object obj)
- {
- PropertyInfo[] fields = obj.GetType().GetProperties();
- foreach (PropertyInfo v in fields)
- {
- if (v.PropertyType == typeof(string) && v.GetValue(obj) == null)
- {
- v.SetValue(obj, "");
- }
- else if (v.PropertyType == typeof(DateTime) && (v.GetValue(obj) == null || (DateTime)v.GetValue(obj) == DateTime.MinValue))
- {
- v.SetValue(obj, DateTime.Now);
- }
- //else if (v.PropertyType.IsClass && v.GetValue(obj) == null)
- //{
- // EntityFactory.CreateEntity<>();
- //}
- }
- return obj;
- }
- }
- public abstract class EntityFactory
- {
- public static T CreateEntity<T>() where T : class, new()
- {
- T t = Activator.CreateInstance<T>();
- PropertyInfo[] properties = typeof(T).GetProperties();
- foreach (PropertyInfo pi in properties)
- {
- Type type = pi.PropertyType;
- if (type.IsArray)
- {
- pi.SetValue(t, Activator.CreateInstance(type, 10), null);
- }
- else
- {
- pi.SetValue(t, Activator.CreateInstance(type), null);
- }
- }
- return t;
- }
- }
- }
|