public static object invokeSetter(object instance, string key, object value, IConvertSystem converter) { Type instanceType = instance.GetType(); PropertyInfo propertyInfo = instanceType.GetProperty(key); if (null != propertyInfo) { if (!propertyInfo.CanWrite) { return(null); } object oldValue = (propertyInfo.CanRead) ? (propertyInfo.GetValue(instance, null) ?? value) : value; propertyInfo.SetValue(instance, (null == converter) ? value : converter.ConvertTo(value, propertyInfo.PropertyType, null), null); return(oldValue); } else { FieldInfo fieldInfo = instanceType.GetField(key); if (null == fieldInfo) { return(null); } object oldValue = propertyInfo.GetValue(instance, null) ?? value; fieldInfo.SetValue(instance, (null == converter) ? value : converter.ConvertTo(value, propertyInfo.PropertyType, null)); return(oldValue); } }
/// <summary> /// 创建type实例,将properties中的值注入到实例中 /// </summary> /// <returns>创建的实例</returns> public static object CreateObjectFromProperites(IProperties properties, Type type, IConvertSystem convertSystem) { if (null == type) { return(null); } if (null == properties) { return(null); } if (!type.IsClass && !type.IsValueType) { return(null); } if (type.IsAbstract) { return(null); } ConstructorInfo constructorInfo = type.GetConstructor(Type.EmptyTypes); if (null == constructorInfo) { return(null); } object instance = constructorInfo.Invoke(new object[] { }); foreach (KeyValuePair <string, object> kp in properties) { invokeSetter(instance, kp.Key, kp.Value, convertSystem); } return(instance); }