2011-03-16 48 views
1

如果我有一個私有類我可以使用PrivateObject類或Reflection來訪問私有類中的字段嗎?

Class A 
{ 
    public static string foo; 
} 

我可以使用反射來訪問靜態字段?當然,假如我不能改變的代碼...

我的問題是,類在不同的命名空間中定義比我英寸

可以說,我在測試的命名空間,我有對帶有FOO名稱空間的DLL的引用。

namespace FOO 
    { 
    Class A 
    { 
     public static string bar; 
    } 
    } 

我想從命名空間測試接入的A類的酒吧場。

+0

是的,你可以,但要非常小心,這樣做 - 即使它是一個CLR類,它可能會在服務包改變。 – 2011-03-16 09:54:03

回答

1

是的,你可以。你需要獲得Type - 你將如何實現這將取決於你的應用程序的確切性質;例如,Assembly.GetType(string)將是一個選項。之後,你得到FieldInfoType.GetField然後詢問該字段的值,使用null作爲目標,因爲它是一個靜態字段。

+0

謝謝!我結束了使用匯編方法: – 2011-03-16 13:36:46

+0

gee ...我完全錯過了這個類是私人的點.... +1 – 2011-03-16 15:02:05

0

嘗試

object value = typeof (Program).GetFields(BindingFlags.Static | BindingFlags.Public) 
    .Where(x => x.Name == "foo").FirstOrDefault() 
    .GetValue(null); 
+0

無法創建這個類的一個實例,因爲它是私人的... – 2011-03-16 13:35:57

+0

對不起,你做不需要,我更新了。 – Aliostad 2011-03-16 13:47:06

2

這是故意冗長,所以你會得到什麼正在發生的事情一步一步來。它檢查類型A中的所有字段並查找名爲「foo」的字段。

編輯:它也適用於A在不同的命名空間。

namespace DifferentNamespace 
{ 
    class A 
    { 
     public static string foo = "hello"; 
    } 
} 

class Program { 
    static void Main(string[] args) { 
     Type type = typeof(DifferentNamespace.A); 
     FieldInfo[] fields = type.GetFields(); 
     foreach (var field in fields) 
     { 
      string name = field.Name; 
      object temp = field.GetValue(null); // Get value 
               // since the field is static 
               // the argument is ignored 
               // so we can as well pass a null     
      if (name == "foo") // See if it is named "foo" 
      { 
       string value = temp as string; 
       Console.Write("string {0} = {1}", name, value); 
      } 
      Console.ReadLine(); 
     } 
    } 
} 
+1

它不適用於我使用另一個命名空間..編譯時,我得到「DifferentNamespace.A由於它的保護級別而不可訪問」錯誤 – 2011-03-16 11:05:57

1

什麼終於爲我工作是大會的方式:

assembly = typeof(Class B).Assembly; //Class B is in the same namespace as A 
Type type = assembly.GetType("FOO.A"); 
string val = (string) type.GetField("bar", 
    BindingFlags.Public | BindingFlags.Static).GetValue(null); 
相關問題