Thursday, February 27, 2014

CSharp C# Simple example of changing an objects variables with Reflection

CSharp C# Simple example of changing an objects variables with Reflection





using System;

namespace ReflectVariable
{
    class Program
    {
        static void Main(string[] args)
        {
            //Instantiate object with initial values:
            ReflectVariableTest ReflectVariableTestNow = new ReflectVariableTest();
            ReflectVariableTestNow.MyString = "The Initial Value";
            ReflectVariableTestNow.MyInt = 1;
           
            //Console out the values set initially:
            Console.WriteLine("ReflectVariableTestNow.MyString (A) ={0}", ReflectVariableTestNow.MyString);
            Console.WriteLine("ReflectVariableTestNow.MyInt(A) ={0}", ReflectVariableTestNow.MyInt);
           
            //Change the two values:
            UpdateValueOfStringValue("The New Value", ReflectVariableTestNow, "MyString");
            UpdateValueOfIntValue(2, ReflectVariableTestNow, "MyInt");
           
            Console.WriteLine();
           
            //Console out the values as changed:
            Console.WriteLine("ReflectVariableTestNow.MyString (B) ={0}", ReflectVariableTestNow.MyString);
            Console.WriteLine("ReflectVariableTestNow.MyInt(B) ={0}", ReflectVariableTestNow.MyInt);
           
            Console.WriteLine("Done.  Hit the enter key");
            Console.ReadLine();
        }

        public static void UpdateValueOfStringValue(string ValueNow, object ClassToReflect, string FieldNameNow)
        {
            Type TypeNow = ClassToReflect.GetType();         
            System.Reflection.FieldInfo FieldToModify = TypeNow.GetField(FieldNameNow);
            FieldToModify.SetValue(ClassToReflect, ValueNow);
        }

        public static void UpdateValueOfIntValue(int ValueNow, object ClassToReflect, string FieldNameNow)
        {
            Type TypeNow = ClassToReflect.GetType();
            System.Reflection.FieldInfo FieldToModify = TypeNow.GetField(FieldNameNow);
            FieldToModify.SetValue(ClassToReflect, ValueNow);
        }
    }

    public class ReflectVariableTest
    {
        public string MyString//Note that {get; set;} makes this not read as a Field
        public int MyInt;
    }
}



No comments:

Post a Comment