using System;
using System.Reflection;
using System.Globalization;
publicclass MyClass
{
privatestring myString;
public MyClass()
{
myString ="Old value";
} string GetField
{
get {
return myString;
} } } publicclass FieldInfo_SetValue
{
publicstaticvoid Main()
{
try {
MyClass myObject =new MyClass();
Type myType = Type.GetType("MyClass");
FieldInfo myFieldInfo = myType.GetField("myString", BindingFlags.NonPublic | BindingFlags.Instance);
// Display the string before applying SetValue to the field. Console.WriteLine( " The field value of myString is {0}.", myFieldInfo.GetValue(myObject));
// Display the SetValue signature used to set the value of a field. Console.WriteLine( "Applying SetValue(Object, Object).");
// Change the field value using the SetValue method. myFieldInfo.SetValue(myObject, "New value");
// Display the string after applying SetValue to the field. Console.WriteLine( "The field value of mystring is {0}.", myFieldInfo.GetValue(myObject));
// Set the field value to its old value. myFieldInfo.SetValue( myObject , "Old value" );
myFieldInfo = myType.GetField("myString", BindingFlags.NonPublic | BindingFlags.Instance);
// Display the string before applying SetValue to the field. Console.Write( " The field value of mystring is {0}. ", myFieldInfo.GetValue(myObject));
// Display the SetValue signature used to set the value of a field. Console.WriteLine("Applying SetValue(Object, Object, BindingFlags, Binder, CultureInfo).");
// Change the field value using the SetValue method. myFieldInfo.SetValue(myObject, "New value", BindingFlags.Public, null, null);
// Display the string after applying SetValue to the field. Console.WriteLine( "The field value of mystring is {0}.", myFieldInfo.GetValue(myObject));
} catch( Exception e )
{
// Any exception generated is displayed. Console.WriteLine( "Exception: {0}", e.Message );
} } }