2009-06-08 31 views

回答

5

Here是做,在.NET

using System; 
using System.Reflection; 
using System.Collections.Generic; 

public class MyClass 
{ 
    public static void Main() 
    { 
     try 
     { 
      Console.WriteLine("TestReflect started."); 
      TestReflect test = new TestReflect(); 
      Console.WriteLine("TestReflect ended."); 
     } 
     catch (Exception ex) 
     { 
      Console.WriteLine(ex.ToString()); 
     } 

     ConsoleKeyInfo cki; 
     do 
     { 
      Console.WriteLine("Press the 'Q' key to exit."); 
      cki = Console.ReadKey(true); 
     } while (cki.Key != ConsoleKey.Q); 
    } 
} 

public class TestReflect 
{ 
    public TestReflect() 
    { 
     this.GetType().GetMethod("PublicMethod").Invoke(this, null); 
     this.GetType().GetMethod("PrivateMethod", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(this, null); 
    } 

    public void PublicMethod() 
    { 
     Console.WriteLine("PublicMethod called"); 
    } 

    private void PrivateMethod() 
    { 
     Console.WriteLine("FTW!one1"); 
    } 
} 
+0

鏈接已損壞。如果你在從網站上抄下有用的內容之前,它們會很好,現在這個被接受的答案是沒有用的。 – NightOwl888 2016-10-13 14:00:45

+1

@ NightOwl888,爲你修好。 – Yishai 2016-10-13 15:06:54

2

它在.NET很可能獲得訪問任何私人使用反射。

E.g得到ACCES上課欄上叫Foo的私有實例方法看起來像:

typeof(Bar).GetMethod("Foo",BindingFlags.NonPublic | BindingFlags.Instance); 

但它確實需要使用反射的代碼是完全可信的。

(V4的安全要求會有所不同)

相關問題