About PropertyInfo SetValue () and PropertyInfo GetValue ()

Source: Internet
Author: User

var property = obj. GetType (). GetProperty ("PropertyName");

Represents a property that gets the class obj PropertyName

propertyinfo[] Propertys = T.gettype (). GetProperties ();

Represents getting all the properties of a class T

Traverse all properties of this object
foreach (PropertyInfo pi in Propertys)
{
Tempname = Pi. name;//Assigning a property name to a temporary variable
Check if DataTable contains this column (column name = = Property Name of object)
if (dt. Columns.contains (Tempname))
{
Determine if this property has a setter
if (!pi. CanWrite) continue;//This property is not writable and jumps directly out
Take value
Object value = Dr[tempname];
If not null, the property assigned to the object
if (value! = DBNull.Value)
Pi. SetValue (t, value, NULL);
}
}

The SetValue method is used when assigning values to a class's properties using reflection

This method has 3 parameters, the first represents the class T, the second represents the property value, and the 3rd explains in detail

The property type is a known base type that can be passed directly to the variable, for example: string

var value= "wangheng.org";

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.

If the original value is a different type. Example: the target type is int and the value is string

String Value= "100″;

Property. SetValue (Obj,int. TryParse (value), null);//Type conversion.


GetValue (Obj,null)

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.