I am learning how to call a method dynamically based on a method name passed as a string. The best way I could understand is invoking a method. I am trying to invoke a method by passing its class name and method name. But it always gives me the exception
Method not found.
I have tried clean up and rebuild all. Still it's not working.
namespace TestInvoking
{
class Invoke
{
public string InvokeMember(string method, string para)
{
try
{
string Result = (string)typeof(Invoke).InvokeMember(method, BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase
| BindingFlags.NonPublic | BindingFlags.InvokeMethod,
null, null, new Object[] { para });
return Result;
}
catch (MissingMemberException e)
{
MessageBox.Show("Unable to access the testMethod field: {0}", e.Message);
return null;
}
}
public void testMethod(string tri)
{
MessageBox.Show("methodInvoked - {0}", tri);
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Invoke methodInvoke = new Invoke();
text.Text = methodInvoke.InvokeMember("testMethod", "Method_Invoked");
}
You have a couple of problems.
BindingFlags.Static
but the method is not static.null
to the target. As long as the InvokeMember
is not
static, hence you already have an instance, you could just pass the
parameter.After doing both changes the code would be as follows.
class Invoke
{
public string InvokeMember(string method, string para)
{
try
{
string Result = (string)typeof(Invoke).InvokeMember(method, BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.InvokeMethod, null, this, new Object[] { para });
return Result;
}
catch (MissingMemberException e)
{
MessageBox.Show("Unable to access the testMethod field: {0}", e.Message);
return null;
}
}
public void testMethod(string tri)
{
MessageBox.Show("methodInvoked - {0}", tri);
}
}