2009-06-08 48 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的安全要求会有所不同)

相关问题