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

C# 在运行时使用反射修改实例变量,c#,reflection,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 Ad

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

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

提前感谢。

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

存在多个问题

首先,您传递的是
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);
所以它为你做了

此外,您还需要将
Addition
的实例传递到
GetValue
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

您需要将实例传递给SetValue。@SimonWhitehead filedinfo本身为空。所以它甚至不会进入if条件。我在下面提供了一个答案。即使我使用BindingFlag.Public,filedinfo也会显示为null。我已经编辑了这个问题。你忘记了绑定标志。除了公众的例子。现在是罚款。我必须将加法clas对象传递到getValue和Setvalue中。我已经相应地编辑了我的文章。。谢谢