using System; using System.Reflection; namespace DelphiProjectHandler.Tests.Utilities { /// /// Runs static and non-static private methods. /// public class MethodRunner { /// /// Runs a private method of an object instance. /// /// Existing object instance. /// Method to run. /// Parameters for the method. /// Result of running the method. public static object RunInstance(object iObject, string iMethodName, object[] iParams) { BindingFlags vFlags = BindingFlags.Instance; return RunMethod(iObject.GetType(), iObject, vFlags, iMethodName, iParams); } /// /// Runs a private static method of a class. /// /// Class type. /// Method to run. /// Parameters for the method. /// Result of running the method. public static object RunStatic(Type iType, string iMethodName, object[] iParams) { BindingFlags vFlags = BindingFlags.Static; return RunMethod(iType, null, vFlags, iMethodName, iParams); } /// /// Runs a private static or non-static method of a class or existing object instance. /// /// Class type. /// Existing object instance. /// Flags used when searching for the method. /// By default BindingFlags.NonPublic and BindingFlags.Public will be /// added. /// Method to run. /// Parameters for the method. /// Result of running the method. protected static object RunMethod(Type iType, object iObject, BindingFlags iBindingFlags, string iMethodName, params object[] iParams) { iBindingFlags = iBindingFlags | BindingFlags.NonPublic | BindingFlags.Public; MethodInfo vMethodInfo = iType.GetMethod(iMethodName, iBindingFlags); if (vMethodInfo == null) throw new ArgumentException("Private method " + iMethodName + " was not found in type " + iType.ToString()); return vMethodInfo.Invoke(iObject, iParams); } } }