リフレクションを使用して、署名:someobject.somegenericinstancemethod (t引数)を使用して、オブジェクトインスタンスでジェネリックメソッドを呼び出す
-
12-10-2019 - |
質問
どのように電話しますか SomeObject.SomeGenericInstanceMethod<T>(T arg)
?
一般的な方法を呼び出すことについてのいくつかの投稿がありますが、このようなものとはまったく異なります。問題は、メソッド引数パラメーターが汎用パラメーターに制約されていることです。
代わりに署名があったかどうかを知っています
SomeObject.SomeGenericInstanceMethod<T>(string arg)
その後、MethodInfoを取得できます
typeof (SomeObject).GetMethod("SomeGenericInstanceMethod", new Type[]{typeof (string)}).MakeGenericMethod(typeof(GenericParameter))
それでは、通常の引数が一般的なタイプの場合、MethodInfoを取得するにはどうすればよいですか?ありがとう!
また、一般的なパラメーターにタイプ制約がある場合とそうでない場合があります。
解決
あなたはまったく同じようにそれをします。
methodinfo.invokeに電話すると、すべての引数をに渡します object[]
とにかく、コンパイル時にタイプを知る必要があるわけではありません。
サンプル:
using System;
using System.Reflection;
class Test
{
public static void Foo<T>(T item)
{
Console.WriteLine("{0}: {1}", typeof(T), item);
}
static void CallByReflection(string name, Type typeArg,
object value)
{
// Just for simplicity, assume it's public etc
MethodInfo method = typeof(Test).GetMethod(name);
MethodInfo generic = method.MakeGenericMethod(typeArg);
generic.Invoke(null, new object[] { value });
}
static void Main()
{
CallByReflection("Foo", typeof(object), "actually a string");
CallByReflection("Foo", typeof(string), "still a string");
// This would throw an exception
// CallByReflection("Foo", typeof(int), "oops");
}
}
他のヒント
あなたはまったく同じ方法でそれを行いますが、あなたのオブジェクトのインスタンスを渡します:
typeof (SomeObject).GetMethod(
"SomeGenericInstanceMethod",
yourObject.GetType())
// Or typeof(TheClass),
// or typeof(T) if you're in a generic method
.MakeGenericMethod(typeof(GenericParameter))
makegenericmethod メソッドでは、メソッドの引数ではなく、汎用型パラメーターを指定する必要のみです。
メソッドを呼び出すと、後で引数を渡します。しかし、この時点で、彼らはASを通り過ぎています object
, 、だからそれは再び問題ではありません。