I would like to know if there is a way in c# to execute a method, if we have only it's name in a string ?
string methodname="method"
this.RunMethod(methodname)
Something like that ?
Thanks :)
I would like to know if there is a way in c# to execute a method, if we have only it's name in a string ?
string methodname="method"
this.RunMethod(methodname)
Something like that ?
Thanks :)
Try this:
Type t = Type.GetType(typeName);
t.InvokeMember("method", BindingFlags.InvokeMethod | BindingFlags.Public, null, null, null);
Something like
Type type = GetType("MyType");
MethodInfo methodInfo = type.GetMethod(methodName);
methodInfo.Invoke()
I used seomthing like this:
typeof(StringValidator<T>).GetMethod(restriction.Operacion.Nombre).Invoke(null, param) as IList<T>;
based on the type of the class that contains the method (StringValidator) then I get the method by it's name restriction.Operacion.Nombre, and Invoke it.
hope it helps
This example has what you are looking for namely:
String s = (String)calledType.InvokeMember(
methodName,
BindingFlags.InvokeMethod | BindingFlags.Public |
BindingFlags.Static,
null,
null,
null);
(Obviously this may change depending on return types etc.)
You need the type, the method name, and an instance if the method is not static
You can create a generic method to invoke methods by their name on any instance you want this way:
public void RunMethodOn(object obj, String methodName,params Object[] args)
{
if(obj != null)
{
System.Reflection.MethodInfo method = null;
method = obj.GetType().GetMethod(methodName);
if (method != null)
method.Invoke(obj, args);
}
}
And the use it to call a method on your own instance as you ask:
public void RunMethod(String methodName,params Object[] args)
{
ExecuteOn(this, methodName, args);
}
You can do this very nicely with an extension method:
public static class MethodEx
{
public static void RunMethod(
this object target,
string methodName,
params object[] values)
{
var type=target.GetType();
var mi =
type.GetMethod(methodName,values.Select(v=>v.GetType()).ToArray());
mi.Invoke(target,values);
}
}
...and use it as follows:
void Main()
{
var m=new Monkey();
m.RunMethod("A",1);
m.RunMethod("A","frog");
}
class Monkey
{
public void A(int a)
{
Console.WriteLine("int A called");
}
public void A(string s)
{
Console.WriteLine("string A called");
}
}
which will choose the right overload according to the supplied params, so the code above gives output:
int A called
string A called
I leave better error handling to the OP.