setAccessibleを見てください - Javaでリフレクションでプライベートメソッドを呼び出す方法です。なぜ.NETはそのような機能を実装していないのですか?.NETにJavaのsetAccessibleと並行しているのはなぜですか?
3
A
答えて
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");
}
}
2
に、私は「なぜ」投機質問のビットかもしれないと思うが、あなたはプライベートメソッドをテストする方法を探しているなら、私が思うことをやっての一例ですあなたは、.NET 4.0でこれを簡単に行うことができるようになります:あなたはそれがパブリックメソッドを呼び出すほど単純ではないですが、プライベートメソッドを呼び出すためにリフレクションを使用することができます
http://bugsquash.blogspot.com/2009/05/testing-private-methods-with-c-40.html
4
。私たちは、ユニットテストのために前にこれをやったと使い方を参照するとして、次の記事を使用しています
http://www.emadibrahim.com/2008/07/09/unit-test-private-methods-in-visual-studio/
http://johnhann.blogspot.com/2007/04/unit-testing-private-methods.html
2
それはリフレクションを使用して、民間のものへのアクセスを取得するには、.NETにはかなり可能です。
例えば、クラスバーにはFooというプライベートインスタンスメソッドへのアクセスもは次のようになります取得:
typeof(Bar).GetMethod("Foo",BindingFlags.NonPublic | BindingFlags.Instance);
それはしかし、コード使用して反射が完全に信頼されていることを必要とします。
(セキュリティ要件はV4と異なります)
リンクが壊れています。彼らはそれを取り下げる前に、サイトからの有用なビットをコピーしたなら、これは受け入れられた答えは役に立たないといいですね。 – NightOwl888
@ NightOwl888、あなたのためにそれを修正しました。 – Yishai