Invoke an object's public methods by using their names in C#
You can use reflection to call an object's methods by using their names as shown in the following code.
// Invoke the method.The code uses GetType to get the class's type information. It then calls GetMethod to get a MethodInfo object describing the method. 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. The following code shows the methods available in this example.
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 public methods to invoke.Reflection lets you do lots of other things with objects such as learn about and invoke their properties, methods, and events.
public void Method1()
{
MessageBox.Show("This is Method 1");
}
public void Method2()
{
MessageBox.Show("This is Method 2");
}


Comments