C # modifying the value through the object property name,
From: csdn can assign values to an object attribute in the PropertyInfo. SetValue () mode. Note that the value type must be consistent with the attribute.
Two methods to create an object instance:
1.
var obj = Assembly.Load("AssemblyName").CreateInstance("AssemblyName"+"ClassFullName");
2. var obj = Activator. CreateInstance (ClassType );
When creating an instance, you can assign a value to an attribute of the current instance. First, obtain the attribute to be assigned.
Var property = obj. GetType (). GetProperty ("PropertyName"); // you can use GetProperty to obtain the attribute array and assign values cyclically. The type problem is explained here.
You can use the PropertyInfo. SetValue () method to assign values. For details, see MSDN.
Case 1: The property type is a known type, for example: int
int value=500;property.SetValue(obj,value,null);
Note that the value type must be the same as the attribute type. Otherwise, a TargetException is thrown.
Case 2: The attribute type is known and the original value is of another type. For example, the target type is int and the value is string.
String value = "500"; property. SetValue (obj, int. TryParse (value), null); // type conversion.
The first two cases are simple. Sometimes the business is complicated and the target type is uncertain. You need to determine when the program is running.
Case 3: The attribute type is unknown and non-generic. The target type is uncertain and how to convert the type.
Object value = "500"; property. SetValue (obj, Convert. ChangeType (value, property. PropertyType), null); // type conversion.
In this way, most problems can be solved.
I don't know if you have noticed that I have emphasized the non-generic type in the third case. Isn't it possible for the generic type to work?
Yes. If you only use the Convert. ChangeType () method, type conversion still reports an error. first look at the following code.
Even if the target type and value type are the same, an error is returned when Convert. ChangeType () is used for conversion.
To solve this problem, Convert the attribute value type to the base type before Convert conversion. As shown in the code, no error will be reported when Convert. ChangeType () is used to Convert Null Types.
Some basic judgment and verification are added to improve the code.
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 (property. PropertyType), null );}}