2009-05-02 32 views
1

有沒有辦法通過反射來執行「內部」代碼?c#,內部和反射

下面是一個例子程序:

using System; 
using System.Reflection; 

namespace ReflectionInternalTest 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      Assembly asm = Assembly.GetExecutingAssembly(); 

      // Call normally 
      new TestClass(); 

      // Call with Reflection 
      asm.CreateInstance("ReflectionInternalTest.TestClass", 
       false, 
       BindingFlags.Default | BindingFlags.CreateInstance, 
       null, 
       null, 
       null, 
       null); 

      // Pause 
      Console.ReadLine(); 
     } 
    } 

    class TestClass 
    { 
     internal TestClass() 
     { 
      Console.WriteLine("Test class instantiated"); 
     } 
    } 
} 

創建TestClass的正常工作完美,但是當我嘗試創建通過反射一個實例,我得到一個錯誤missingMethodException說,它不能找到構造函數(其如果你嘗試從組件外部調用它會發生什麼)。

這是不可能的,還是有一些解決方法,我可以做?

回答

4

基於Preets方向到備用柱:

using System; 
using System.Reflection; 
using System.Runtime.CompilerServices; 

namespace ReflectionInternalTest 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      Assembly asm = Assembly.GetExecutingAssembly(); 

      // Call normally 
      new TestClass(1234); 

      // Call with Reflection 
      asm.CreateInstance("ReflectionInternalTest.TestClass", 
       false, 
       BindingFlags.Default | BindingFlags.CreateInstance | BindingFlags.Instance | BindingFlags.NonPublic, 
       null, 
       new Object[] {9876}, 
       null, 
       null); 

      // Pause 
      Console.ReadLine(); 
     } 
    } 

    class TestClass 
    { 
     internal TestClass(Int32 id) 
     { 
      Console.WriteLine("Test class instantiated with id: " + id); 
     } 
    } 
} 

這工作。 (增加了一個論據來證明它是一個新實例)。

事實證明我只是需要實例和非公有的BindingFlags。

5

下面是一個例子...

class Program 
    { 
     static void Main(string[] args) 
     { 
      var tr = typeof(TestReflection); 

      var ctr = tr.GetConstructor( 
       BindingFlags.NonPublic | 
       BindingFlags.Instance, 
       null, new Type[0], null); 

      var obj = ctr.Invoke(null); 

      ((TestReflection)obj).DoThatThang(); 

      Console.ReadLine(); 
     } 
    } 

    class TestReflection 
    { 
     internal TestReflection() 
     { 

     } 

     public void DoThatThang() 
     { 
      Console.WriteLine("Done!") ; 
     } 
    } 
+0

只是一個快速一絲AccessPrivateWrapper動態包裝,你可以使用Types.EmptyTypes,而不是新類型[0]。 – Vinicius 2013-02-08 18:51:21