2009-05-02 57 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