August 2003
Intermediate to advanced
928 pages
32h 1m
English
The preceding example demonstrates the use of reflection, but doesn’t perform any tasks you can’t accomplish using normal C# language constructs. However, reflection can also manipulate types in ways not supported directly in C#, as demonstrated in this section.
While the CLR enforces access controls on type members (specified
using access modifiers such as private and protected), these
restrictions don’t apply to reflection. Assuming you
have the correct set of permissions, you can use reflection to access
and manipulate private data and function members, as this example
using the Greeting subtypes from the previous
section shows (see the source comment for filename and compilation
information):
// InControl.cs - compile with /r:Greeting.dll,English.dll using System; using System.Reflection; class TestReflection { // Note: This method requires the ReflectionPermission perm. static void ModifyPrivateData(object o, string msg) { // Get a FieldInfo type for the private data member Type t = o.GetType( ); FieldInfo fi = t.GetField("msg", BindingFlags.NonPublic| BindingFlags.Instance); // Use the FieldInfo to adjust the data member value fi.SetValue(o, msg); } static void Main( ) { // Create instances of both types BritishGreeting bg = new BritishGreeting( ); AmericanGreeting ag = new AmericanGreeting( ); // Adjust the private data via reflection ModifyPrivateData(ag, "Things are not the way they seem"); ModifyPrivateData(bg, "The runtime is in total control!"); ...