How C # Modifies an instance of a value by object property name

Source: Internet
Author: User

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);                }            }
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.