Skip to content

Instantly share code, notes, and snippets.

@AlexArchive
Created August 23, 2013 11:53
Show Gist options
  • Save AlexArchive/6318504 to your computer and use it in GitHub Desktop.
Save AlexArchive/6318504 to your computer and use it in GitHub Desktop.
public static class MethodInvoker
{
public static object InvokeMethod(string methodName, object[] paramaters = null)
{
MethodInfo method = ResolveMethodWithName(methodName);
if (method == null)
throw new InvalidOperationException("A method with the name " + methodName + " cannot be found.");
if (method.IsStatic)
{
return method.Invoke(null, paramaters);
}
if (method.DeclaringType != null)
{
object instance = Activator.CreateInstance(method.DeclaringType);
return method.Invoke(instance, paramaters);
}
throw new InvalidOperationException("This Should Never Throw Unless I Forgot Something");
}
private static MethodInfo ResolveMethodWithName(string methodName)
{
Assembly executingAssembly = Assembly.GetExecutingAssembly();
return executingAssembly
.GetTypes()
.SelectMany(type => type.GetMethods(MethodBindingFlags))
.FirstOrDefault(method => method.Name == methodName);
}
private const BindingFlags MethodBindingFlags =
BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.Static;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment