运行时使用反射修改实例变量

时间:2013-10-02 05:06:01

标签: c# reflection

我已经通过以下代码。在这里,我无法在运行时获取/设置变量的值。变量值已通过控制台获取。

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace ReflectionTest
{
    class Addition
    {
        public  int a = 5, b = 10, c = 20;
        public Addition(int a)
        {
            Console.WriteLine("Constructor called, a={0}", a);
        }
        public Addition()
        {
            Console.WriteLine("Hello");
        }
        protected Addition(string str)
        {
            Console.WriteLine("Hello");
        }

    }

    class Test
    {
        static void Main()
        {
            //changing  variable value during run time
            Addition add = new Addition();
            Console.WriteLine("a + b + c = " + (add.a + add.b + add.c));
            Console.WriteLine("Please enter the name of the variable that you wish to change:");
            string varName = Console.ReadLine();
            Type t = typeof(Addition);
            FieldInfo fieldInfo = t.GetField(varName ,BindingFlags.Public);
            if (fieldInfo != null)
            {
                Console.WriteLine("The current value of " + fieldInfo.Name + " is " + fieldInfo.GetValue(add) + ". You may enter a new value now:");
                string newValue = Console.ReadLine();
                int newInt;
                if (int.TryParse(newValue, out newInt))
                {
                    fieldInfo.SetValue(add, newInt);
                    Console.WriteLine("a + b + c = " + (add.a + add.b + add.c));
                }
                Console.ReadKey();
            }
       }
    }
  }

提前致谢..

2 个答案:

答案 0 :(得分:1)

您的类中的字段是特定于实例的并且是公共的,但您使用的是中午公共绑定标志而不是公共绑定标志,而不是应用实例绑定标志(使用|用于按位或)。

答案 1 :(得分:1)

有很多问题。

首先,你正在通过BindingFlags.NonPublic。这不行。您需要像这样传递BindingFlags.PublicBindingsFlags.Instance

t.GetField(varName, BindingFlags.Public | BindingFlags.Instance);

或者,根本不要这样做:

t.GetField(varName);

您可以根本不传递任何内容,因为GetField的实现是这样的:

return this.GetField(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public);

所以它适合你。

此外,您需要将Addition的实例传递给GetValueSetValue,如下所示:

Console.WriteLine("The current value of " + 
    fieldInfo.Name + 
    " is " + 
    fieldInfo.GetValue(add) + ". You may enter a new value now:");
//                     ^^^ This

.. ..和

fieldInfo.SetValue(add, newInt);
//                 ^^^ This