質問
" internal"を実行する方法はありますか?リフレクション経由のコード?
プログラムの例を次に示します。
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");
}
}
}
テストクラスの作成は通常完全に機能しますが、リフレクションを介してインスタンスを作成しようとすると、Constructorが見つからないことを示すmissingMethodExceptionエラーが表示されます(アセンブリの外部から呼び出した場合に発生します) 。
これは不可能ですか、または回避策はありますか?
解決 2
別の投稿への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だけが必要でした。
他のヒント
例を示します...
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!") ;
}
}
C#4.0を使用している場合は、AccessPrivateWrapper動的ラッパーを使用します http://amazedsaint.blogspot.com/2010/05/accessprivatewrapper-c-40-dynamic.html
所属していません StackOverflow