Created
August 23, 2013 11:53
-
-
Save AlexArchive/6318504 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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