Simple operation of C # Reflection technology (read and set properties of Class) _ Practical Tips

Source: Internet
Author: User
Tags reflection

To have a dynamic assignment or value to a property or field of an instance of a type, you first have to get the type of that instance, or the types, Microsoft has provided us with enough methods.
First, set up a test class

Copy Code code as follows:

public class MyClass
public int one {set;
public int two {set; get;}
public int five {set; get;}
public int three {set; get;}
public int four {set; get;}

then write the code that reflects the class
Copy Code code as follows:

MyClass obj = new MyClass ();
Type t = typeof (MyClass);
Loop Assignment
int i = 0;
foreach (var item in t.getproperties ())
Item. SetValue (obj, I, null);
i + 1;
Assign values individually
T.getproperty ("Five"). SetValue (obj, 11111111, null);
Loop fetch
StringBuilder sb = new StringBuilder ();
foreach (var item in t.getproperties ())
Sb. Append ("type:" + item.) Propertytype.fullname + "Property name:" + Item. Name + "Value:" + Item. GetValue (obj, null) + "<br/>");
Individual values
int five = Convert.ToInt32 (T.getproperty ("Five"). GetValue (obj, null));
Sb. Append ("Five value alone:" + five);
string result = sb. ToString ();
Response.Write (Result);

Test Display results:
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
Value of five alone: 11111111

Well, once you know the properties of a class are reflected, you may be able to think of a way to do it, that is, T. GetProperties () changed to T. GetMethods (), Operation Method Ditto.

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: 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.