Assigning values to an object property can be assigned by Propertyinfo.setvalue (), but be aware that the type of the value is consistent with the property.
Creating an Object instance
1>
var obj = Assembly.Load(
"AssemblyName"
).CreateInstance(
"AssemblyName"
+
"ClassFullName"
);2>
var obj = Activator.CreateInstance(ClassType);
Assign Value
var property = obj.GetType().GetProperty(
"PropertyName"
);
//此时可以使用GetProperty获取属性数组,循环进行赋值,这里主要讲解类型问题。1> The property type is a known type, for example: int
int
value=500;
property.SetValue(obj,value,
null
);2> The property type is a known type and the original value is another type. Example: the target type is int and the value is string
string
value=
"500"
;
property.SetValue(obj,
int
.TryParse(value),
null
);
//类型转换。3> The property type is an unknown non-generic type, the target type is not determined, and the type conversion is done.
object
value=
"500"
;
property.SetValue(obj,Convert.ChangeType(value,property.PropertyType),
null
);
//类型转换。
Problems encountered in C # reflection to Object assignment--type conversion