using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace JiepeiWMS.Common { /// ///对象实例操作类 /// public class ComRefObj { /// ///构造对象实例操作类 /// public ComRefObj(object Obj) { _Obj = Obj; _Type = Obj.GetType(); _Attrs = _Type.GetProperties(); } /// ///构造对象实例操作类 /// public ComRefObj(Type Tp) { _Obj = Tp; _Type = Tp; _Attrs = _Type.GetProperties(); } object _Obj; Type _Type; PropertyInfo[] _Attrs; /// /// 获取对象的属性值(不区分大小写属性名) /// /// 属性值 public T GetAttr(string Name) { return GetAttr(Name, default(T)); } /// /// 获取对象的属性值(不区分大小写属性名) /// /// 属性值 public T GetAttr(string Name, T DefaultValue) { Name = Name.ToLower(); var i = _Attrs.FirstOrDefault(it => it.Name.ToLower() == Name); if (i == null) { return DefaultValue; } return (T)i.GetValue(_Obj, null); } /// /// 获取对象的属性值 /// /// 属性值 public T GetAttr(string Name, bool IsIgnoreCase, T DefaultValue = default(T)) { System.Reflection.PropertyInfo p; if (IsIgnoreCase) { Name = Name.ToLower(); p = _Attrs.FirstOrDefault(t => t.Name.ToLower() == Name); } else { p = _Attrs.FirstOrDefault(t => t.Name == Name); } if (p == null) { return (T)DefaultValue; } return (T)p.GetValue(_Obj, null); } /// /// 获取对象的属性值 /// /// 属性值 public object GetAttr(string Name, bool IsIgnoreCase) { System.Reflection.PropertyInfo p; if (IsIgnoreCase) { Name = Name.ToLower(); p = _Attrs.FirstOrDefault(t => t.Name.ToLower() == Name); } else { p = _Attrs.FirstOrDefault(t => t.Name == Name); } if (p == null) { return null; } return p.GetValue(_Obj, null); } /// /// 设置对象的属性值(不区分大小写属性名) /// /// 自身 public ComRefObj SetAttr(string Name, T Value) { Name = Name.ToLower(); var i = _Attrs.FirstOrDefault(it => it.Name.ToLower() == Name); if (i != null) { i.SetValue(_Obj, Value, null); } return this; } /// /// 设置对象的属性值 /// /// 自身 public ComRefObj SetAttr(string Name, T Value, bool IsIgnoreCase) { PropertyInfo p; if (IsIgnoreCase) { Name = Name.ToLower(); p = _Attrs.FirstOrDefault(t => t.Name.ToLower() == Name); } else { p = _Attrs.FirstOrDefault(t => t.Name == Name); } if (p != null) { p.SetValue(_Obj, Value, null); } return this; } /// /// 设置模型(只操作属性方法和字段不操作) /// /// 模型类型 /// 被读取属性值的模型 /// 不设置的属性名 /// 自身 public ComRefObj Set(MT Model, string[] NotSetNames) { var pts = Model.GetType().GetProperties().ToDictionary(t => t.Name); foreach (var n in NotSetNames) { if (pts.ContainsKey(n)) { pts.Remove(n); } } PropertyInfo gp; foreach (var p in _Attrs) { if (pts.TryGetValue(p.Name, out gp)) { p.SetValue(_Obj, gp.GetValue(Model, null), null); } } return this; } } }