このコードで:
World w = new World();
var data = GetData<World>(w);
私がw
リフレクションで取得し、これがタイプ、、、などである可能性がWorld
あるAmbient
場合Domention
。
どうすれば入手できますGetData
か?
私はインスタンスオブジェクトしか持っていません:
var data = GetData<???>(w);
var type = <The type where GetData method is defined>;
var genericType = typeof(w);
var methodInfo = type.GetMethod("GetData");
var genericMethodInfo = methodInfo.MakeGenericMethod(genericType);
//instance or null : if the class where GetData is defined is static, you can put null : else you need an instance of this class.
var data = genericMethodInfo.Invoke(<instance or null>, new[]{w});
セクションを書く必要はありません。タイプが宣言されていない場合、C#はジェネリックメソッドのパラメーターのタイプを暗黙的に決定します。一緒に行く:
var data = GetData(w);
これがサンプルです。
public interface IM
{
}
public class M : IM
{
}
public class N : IM
{
}
public class SomeGenericClass
{
public T GetData<T>(T instance) where T : IM
{
return instance;
}
}
そして、あなたはそれを次のように呼ぶかもしれません。
IM a = new M();
SomeGenericClass s = new SomeGenericClass();
s.GetData(a);