2009-06-08 7 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

+1

@ NightOwl888、あなたのためにそれを修正しました。 – Yishai

2

に、私は「なぜ」投機質問のビットかもしれないと思うが、あなたはプライベートメソッドをテストする方法を探しているなら、私が思うことをやっての一例ですあなたは、.NET 4.0でこれを簡単に行うことができるようになります:あなたはそれがパブリックメソッドを呼び出すほど単純ではないですが、プライベートメソッドを呼び出すためにリフレクションを使用することができます

http://bugsquash.blogspot.com/2009/05/testing-private-methods-with-c-40.html

2

それはリフレクションを使用して、民間のものへのアクセスを取得するには、.NETにはかなり可能です。

例えば、クラスバーにはFooというプライベートインスタンスメソッドへのアクセスもは次のようになります取得:

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

それはしかし、コード使用して反射が完全に信頼されていることを必要とします。

(セキュリティ要件はV4と異なります)

関連する問題