C # assign values to attributes of a Class Using Reflection

Source: Internet
Author: User

 

Create a class. The attributes in the class come from an xml file. The attribute name is the same as that of the xml node. Reflection is used to assign values to each attribute in order not to be judged one by one.

 

 

 

Class myclass

{

// Set attributes

Public string profileid {get; set ;}

Public string url {get; set ;}

Public DateTime startdate {get; set ;}

Public bool bonus {get; set ;}

Public int max {get; set ;}

 

// This function is called internally, so it is set to private.

Private void setProperties ()

{

String propertyname = "";

XmlReader xr = XmlReader. Create (@ "a. xml ");

While (xr. Read ())

{

If (xr. IsStartElement ())

{

// Assign values to attributes

Propertyname = xr. LocalName. ToLower ();

Xr. Read ();

If (propertyname! = "")

{

// Check whether the property exists. If yes, the value is assigned. Otherwise, an error occurs.

If (this. GetType (). GetProperty (propertyname )! = Null)

{

// Convert. ChangeType is used for implementation.

// However, if the value of bonus in xml is 1, an error occurs. It seems that it cannot be converted to the bool type. Therefore, in xml, I forced to write false and true.

This. GetType (). GetProperty (propertyname). SetValue (this, Convert. ChangeType (xr. Value, this. GetType (). GetProperty (propertyname). 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.