Я прошел через приведенный ниже код. Здесь я не могу получить/установить значение переменной во время выполнения. Значение переменной принимается через консоль.Изменение переменной экземпляра во время выполнения с использованием отражения
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();
}
}
}
}
Заранее спасибо ..
Вы должны передать свой экземпляр SetValue. –
@SimonWhitehead filedinfo сам приходит как null. Таким образом, он даже не попадает в состояние. – Kenta
Я дал ответ ниже. –