0

I have been through the below code . Here i am not able to get/set the value of the variable during runtime . Variable value has been taken through console .

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();
            }
       }
    }
  }

Thanks in advance ..

4

2 回答 2

1

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

于 2013-10-02T05:11:38.567 回答
1

有多个问题。

首先,您正在通过BindingFlags.NonPublic. 这行不通。你需要通过BindingFlags.Public并且BindingsFlags.Instance像这样:

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

或者,根本不这样做:

t.GetField(varName);

你什么都不能传递,因为实现GetField是这样的:

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

所以它为你做。

此外,您需要传递AdditiontoGetValue和的实例SetValue,如下所示:

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
于 2013-10-02T05:16:09.550 回答