Excerpt from: CSDN
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.
There are two ways to create an object instance:
1.
var obj = assembly.load ("AssemblyName"). CreateInstance ("AssemblyName" + "Classfullname");
2.
var obj = activator.createinstance (ClassType);
When you create an instance, you can now assign a value to a property of the current instance, first getting the property that you want to assign the value to.
var property = obj. GetType (). GetProperty ("PropertyName");//You can use GetProperty to get an array of attributes, loop through the assignment, and here are the main types of questions.
Assignments are available through the Propertyinfo.setvalue () method, as detailed in MSDN.
Case 1, the property type is a known type, for example: int
int Value=500;property. SetValue (Obj,value,null);
It is important to note that the type of the value must be the same as the property type, or the targetexception exception will be thrown.
In case 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= "$";p roperty. SetValue (Obj,int. TryParse (value), null);//Type conversion.
The first two cases are simple, sometimes the business is more complex, the target type is uncertain, the program needs to be run-time judgment.
In case 3, the attribute type is unknown to the non-generic type, the target type is not determined, and the type conversion is performed.
Object Value= "a";p roperty. SetValue (Obj,convert.changetype (value,property. PropertyType), null);//Type conversion.
This will solve most of the problems.
I do not know whether people have noticed, I stressed in the third case of non-generic, is not the generics?
Yes. If you just use the Convert.changetype () method, the type conversion still error, first look at the following code.
Even if the type of the target type and the value are consistent, the conversion through Convert.changetype () still makes an error.
To solve this problem, convert the attribute value type to a base type after conversion. Look at the code this way, when you use Convert.changetype () to convert a nullable type, you won't get an error.
Add some basic judgment verification, the code is more perfect.
if (!property. Propertytype.isgenerictype) { //non-generic property . SetValue (obj, String. IsNullOrEmpty (value)? Null:Convert.ChangeType (Value, property. PropertyType), null); } else { //generic nullable<> Type Generictypedefinition = property. Propertytype.getgenerictypedefinition (); if (generictypedefinition = = typeof (nullable<>)) {property . SetValue (obj, String. IsNullOrEmpty (value)? Null:Convert.ChangeType (value, Nullable.getunderlyingtype. PropertyType)), null); } }