Skip to content

Instantly share code, notes, and snippets.

@lwl5219
Last active November 22, 2018 05:06
Show Gist options
  • Save lwl5219/96f6c7e0be2440ae2a9023f373b91cdc to your computer and use it in GitHub Desktop.
Save lwl5219/96f6c7e0be2440ae2a9023f373b91cdc to your computer and use it in GitHub Desktop.
.Net 通过反射的方式调用成员函数
public class Helper
{
/// <summary>
/// Runs a method on a type, given its parameters. This is useful for calling private methods.
/// </summary>
/// <returns>The return value of the called method.</returns>
public static object RunStaticMethod(System.Type t, string strMethod, object[] aobjParams, Type[] types) {
BindingFlags eFlags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
return RunMethod(t, strMethod, null, aobjParams, eFlags, types);
}
public static object RunInstanceMethod(System.Type t, string strMethod, object objInstance, object[] aobjParams, Type[] types) {
BindingFlags eFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
return RunMethod(t, strMethod, objInstance, aobjParams, eFlags, types);
}
private static object RunMethod(System.Type t, string strMethod, object objInstance, object[] aobjParams,
BindingFlags eFlags, Type[] types) {
MethodInfo m;
try {
if (null == types) {
m = t.GetMethod(strMethod, eFlags);
} else {
m = t.GetMethod(strMethod, eFlags, Type.DefaultBinder, types, null);
}
if (m == null) {
throw new ArgumentException("There is no method '" + strMethod + "' for type '" + t.ToString() + "'.");
}
object objRet = m.Invoke(objInstance, aobjParams);
return objRet;
}
catch {
throw;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment