2013-10-02 26 views
0

我已經通過了下面的代碼。在這裏,我無法在運行時獲取/設置變量的值。變量值已通過控制檯執行。運行時使用反射修改實例變量

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

在此先感謝..

+0

您需要將您的實例傳遞給setValue。 –

+0

@SimonWhitehead filedinfo本身就是空的。所以它甚至沒有進入條件。 – Kenta

+0

我在下面提供了一個答案。 –

回答

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 
1

在你的類的字段是特定於實例和公開的,但您使用的是中午截止公開結合的標誌,而不是公衆的結合標誌,而不是應用實例綁定標誌(使用|按位或)。

+0

即使我使用BindingFlag.Public,filedinfo會以null結尾。 我編輯了這個問題。 – Kenta

+0

您忘記了|綁定標誌。除了公衆之外的實例。 –

+0

你現在很好。我必須將Addition clas對象傳遞給getValue和Setvalue。我相應地編輯了我的帖子.. Thankss – Kenta