using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; namespace FLY.OBJComponents.Common { public static class PropertiesManager_JSON { /// <summary> /// 设定参数(属性)的值,触发属性值变化“通知”,writeVal /// </summary> /// <param name="propertyName">属性名</param> /// <param name="val">属性值</param> public static void SetValue(object obj, string propertyName, object v) { PropertyInfo property; try { property = obj.GetType().GetProperty(propertyName); } catch(Exception e) { throw new Exception("PropertiesManager_JSON 类型="+obj.GetType().ToString()+" 不能找到 属性名=" + propertyName, e); } if (property == null) { throw new Exception("PropertiesManager_JSON 类型=" + obj.GetType().ToString() + " 不能找到 属性名=" + propertyName); } if (!property.CanWrite) { throw new Exception("PropertiesManager_JSON 类型=" + obj.GetType().ToString() + " 属性名=" + propertyName +" 不能set"); } if (property != null) { if (v == null) { property.SetValue(obj, v, null); } else if (v.GetType() == property.PropertyType) { property.SetValue(obj, v, null); } else { string json = JsonConvert.SerializeObject(v); v = JsonConvert.DeserializeObject(json, property.PropertyType); property.SetValue(obj, v, null); } } } } }