/// <summary> /// 获取属性对象 /// </summary> /// <param name="instance">对象实例</param> /// <param name="propertyString">属性字符串</param> public static object GetObjectProperty(object instance, string propertyString) { if (propertyString.Length <= 0) { return(null); } string[] propertys = propertyString.Split('.'); object tempObject = instance; for (int i = 0; i < propertys.Length; i++) { string propName = propertys[i]; Type objectType = tempObject.GetType(); FastPropertyInfo fastProperty = null; if (i == propertys.Length - 1) { fastProperty = GetFastPropertyInfo(objectType, propName); if (null != fastProperty && fastProperty.Property.CanRead) { return(fastProperty.Get(tempObject)); } } else { fastProperty = GetFastPropertyInfo(objectType, propName); if (null != fastProperty) { tempObject = fastProperty.Get(tempObject); } } } return(null); }
/// <summary> /// 设置属性值 /// </summary> /// <param name="instance">对象实例</param> /// <param name="propertyString">属性字符串</param> /// <param name="propertyValue">属性值</param> public static void SetObjectProperty(object instance, string propertyString, object propertyValue) { if (propertyString.Length <= 0) { return; } string[] propertys = propertyString.Split('.'); object tempObject = instance; for (int i = 0; i < propertys.Length; i++) { string propName = propertys[i]; Type objectType = tempObject.GetType(); FastPropertyInfo fastProperty = null; if (i == propertys.Length - 1) { fastProperty = GetFastPropertyInfo(objectType, propName); if (null != fastProperty && fastProperty.Property.CanWrite) { fastProperty.Set(tempObject, ObjectHelper.GetObjectFromString(propertyValue.ToString(), fastProperty.Property.PropertyType)); } } else { fastProperty = GetFastPropertyInfo(objectType, propName); if (null != fastProperty) { tempObject = fastProperty.Get(tempObject); } } } }
/// <summary> /// 获取属性值 /// </summary> /// <param name="entity">实体对象</param> /// <param name="propertyName">属性名称</param> public static object GetPropertyValue(object entity, string propertyName) { FastPropertyInfo fastProerty = GetFastProperty(entity.GetType(), propertyName); if (fastProerty != null && fastProerty.Property != null) { return(fastProerty.Get(entity)); } return(null); }
public static FastPropertyInfo GetFastPropertyInfo(this PropertyInfo prop) => FastPropertyInfo.Get(prop);