/// <summary> /// 设置属性值 /// </summary> /// <param name="obj"></param> /// <param name="propertyName"></param> /// <param name="value"></param> public static void SetValue(this object obj, string propertyName, object value, bool isTry = false) { Type type = obj.GetType(); string[] propertyarr = propertyName.Split('.'); PropertyObject property = new PropertyObject { CurrentObject = obj }; if (propertyarr.Length > 1) { for (int i = 0; i < propertyarr.Length; i++) { property = GetProperty(property.CurrentObject, propertyarr[i], true); if (property == null && !isTry) { throw new Exception(string.Format("属性:{0}在对象:{0}中找不到!", propertyarr[i], type.FullName)); } } } var pro = property.CurrentObject.GetType().GetProperty(propertyarr[propertyarr.Length - 1]); if (pro != null) { var classType = TypeUtility.CheckType(pro.PropertyType); var converter = TypeConverterFactory.Create(classType); var safeValue = converter.Convert(value, pro.PropertyType); try { pro.SetValue(property.CurrentObject, safeValue, null); } catch { } } }
/// <summary> /// 根据属性名反射获得值 /// </summary> /// <param name="obj"></param> /// <param name="propertyName"></param> /// <returns></returns> public static object GetValue(this object obj, string propertyName, bool isTry = false, bool newProperty = true) { Type type = obj.GetType(); string[] propertyarr = propertyName.Split('.'); object value = null; PropertyObject property = new PropertyObject { CurrentObject = obj }; for (int i = 0; i < propertyarr.Length; i++) { property = GetProperty(property.CurrentObject, propertyarr[i], newProperty, isTry); if (property == null) { if (isTry) { return(null); } else { throw new Exception(string.Format("属性:{0}在对象:{0}中找不到!", propertyarr[i], type.FullName)); } } } value = property?.Value; return(value); }