C # simple operations of reflection technology (reading and setting class attributes)

Source: Internet
Author: User

To dynamically assign values or values to attributes or fields of A Type instance, you must first obtain the instance or Type. Microsoft has provided enough methods for us.
First, create a test class.

Copy codeThe Code is as follows: public class MyClass
{
Public int one {set; get ;}
Public int two {set; get ;}
Public int five {set; get ;}
Public int three {set; get ;}
Public int four {set; get ;}
}

Then write code that reflects the class
Copy codeThe Code is as follows: MyClass obj = new MyClass ();
Type t = typeof (MyClass );
// Cyclic assignment
Int I = 0;
Foreach (var item in t. GetProperties ())
{
Item. SetValue (obj, I, null );
I + = 1;
}
// Assign values separately
T. GetProperty ("five"). SetValue (obj, 11111111, null );
// Obtain it cyclically
StringBuilder sb = new StringBuilder ();
Foreach (var item in t. GetProperties ())
{
Sb. append ("type:" + item. propertyType. fullName + "attribute name:" + item. name + "value:" + item. getValue (obj, null) + "<br/> ");
}
// Separate values
Int five = Convert. ToInt32 (t. GetProperty ("five"). GetValue (obj, null ));
Sb. Append ("take the five value separately:" + five );
String result = sb. ToString ();
Response. Write (result );

Test result:
Type: System. Int32 property name: one value: 0
Type: System. Int32 property name: two value: 1
Type: System. Int32 property name: five value: 11111111
Type: System. Int32 property name: three Value: 3
Type: System. Int32 property name: four value: 4
Take the five value separately: 11111111

Well, after learning about the use of class property reflection, you may think of the same method, that is, t. change GetProperties () to t. getMethods (). The operation method is the same as above.

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.