03.01.2015 Views

C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

586 ❘ CHAPTER 26 Reflection<br />

The GetSetPersonProperties example program, which is shown in Figure 26-2 and available for<br />

download on this book’s website, uses reflection to get and set a Person class’s fields and properties.<br />

Figure 26-2: The<br />

GetSetPersonProperties example<br />

program uses reflection to get<br />

and set property and field values.<br />

The program uses the following simple Person class.<br />

public class Person<br />

{<br />

public string FirstName { get; set; }<br />

public string LastName { get; set; }<br />

public string Street, City, State, Zip;<br />

}<br />

Most of the program’s code creates the Labels and TextBoxes that it uses to display property and<br />

field values. The following code shows how the program gets values. To save space, I removed the<br />

code that creates the Labels and TextBoxes. Download the example to see all the details.<br />

// The Person object.<br />

private Person ThePerson = new Person()<br />

{<br />

FirstName = "Rufus",<br />

LastName = "Firefly",<br />

Street = "1933 Duck Soup Pl",<br />

City = "Hollywood",<br />

State = "CA",<br />

Zip = "90027"<br />

};<br />

// The Labels and TextBoxes we create.<br />

private List Labels;<br />

private List TextBoxes;<br />

// Display the object's fields and properties.<br />

private void getValuesButton_Click(object sender, EventArgs e)<br />

{<br />

// List fields and properties.<br />

foreach (MemberInfo info in ThePerson.GetType().FindMembers(<br />

MemberTypes.Field | MemberTypes.Property,<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!