I need to call a method via reflection. But the thing is that I don't want to find a method, I want to evaluate it at run-time using arguments. This is what I try to do:
class Program
{
static void Main(string[] args)
{
var type = typeof(Test<int>);
type.InvokeMember("Write", BindingFlags.Instance | BindingFlags.Public | BindingFlags.InvokeMethod,
null, new Test<int>(), new object[] {1, "1"});
// The next call fails
type.InvokeMember("Write", BindingFlags.Instance | BindingFlags.Public | BindingFlags.InvokeMethod,
null, new Test<int>(), new object[] { 2, 2 });
}
}
public class Test<T>
{
public void Write(T arg1, string arg2)
{
Console.Write(arg1);
Console.Write(arg2);
Console.WriteLine(" write1");
}
public void Write<T2>(T arg1, T2 arg2)
{
Console.Write(arg1);
Console.Write(arg2);
Console.WriteLine(" write2");
}
}
The first call works fine but the second one generates an exception saying that Write() was not found. Can I call it using InvokeMember anyhow? I don't want trying to look for all methods and then call something like MakeGenericMethod()
Aucun commentaire:
Enregistrer un commentaire