Title: Invoke public methods by using their names in C#
You can use reflection to invoke public methods by using their names. The following code shows how the example program does this.
// Invoke the method.
private void btnInvoke_Click(object sender, EventArgs e)
{
try
{
Type this_type = this.GetType();
MethodInfo method_info =
this_type.GetMethod(txtMethodName.Text);
method_info.Invoke(this, null);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
The code uses GetType to get the class's type information. It then calls GetMethod, passing it the method's name, to get a MethodInfo object describing the method.
Next it calls that object's Invoke method to invoke the method. The second parameter to this call is an array of parameters that should be sent to the method call.
Reflection lets you do lots of other things with objects such as learn about and invoke their properties and events.
Download the example to experiment with it and to see additional details.
|