2009-05-02 4 views
1

リフレクションによって「内部」コードを実行する方法はありますか?ここでc#、Internal、Reflection

はプログラム例です:通常のTestClassを作成

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"); 
     } 
    } 
} 

は完璧に動作し、私はリフレクション経由でインスタンスを作成しようとすると、しかし、私はこれ(それがコンストラクタを見つけることができないと言ってmissingMethodExceptionエラーを取得しますあなたがアセンブリの外からそれを呼び出そうとした場合に起こることです)。

これは不可能なのですか、それとも私ができる回避策がありますか?別のポストにPreets方向に基づいて、ここで

答えて

4

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

にだけで簡単にヒントある場合は、代わりに新しいタイプのTypes.EmptyTypesを使用することができますAccessPrivateWrapperダイナミックラッパーを使用してください。 – Vinicius