本文整理汇总了C#中System.Reflection.MethodInfo.Invoke方法的典型用法代码示例。如果您正苦于以下问题:C# MethodInfo.Invoke方法的具体用法?C# MethodInfo.Invoke怎么用?C# MethodInfo.Invoke使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Reflection.MethodInfo
的用法示例。
在下文中一共展示了MethodInfo.Invoke方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CallBundleMethod
public static void CallBundleMethod(this IMvxViewModel viewModel, MethodInfo methodInfo, IMvxBundle bundle)
{
var parameters = methodInfo.GetParameters().ToArray();
if (parameters.Count() == 1
&& parameters[0].ParameterType == typeof(IMvxBundle))
{
// this method is the 'normal' interface method
methodInfo.Invoke(viewModel, new object[] { bundle });
return;
}
if (parameters.Count() == 1
&& !MvxSingletonCache.Instance.Parser.TypeSupported(parameters[0].ParameterType))
{
// call method using typed object
var value = bundle.Read(parameters[0].ParameterType);
methodInfo.Invoke(viewModel, new[] { value });
return;
}
// call method using named method arguments
var invokeWith = bundle.CreateArgumentList(parameters, viewModel.GetType().Name)
.ToArray();
methodInfo.Invoke(viewModel, invokeWith);
}
示例2: SpeedofMethod
public SpeedofMethod(MethodInfo Method, object[] Parameter, uint Precision = 1)
{
// Boost speed
Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.RealTime;
Thread.CurrentThread.Priority = ThreadPriority.Highest;
// Warm up
Method.Invoke(null, Parameter);
// Clean up the system
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
// test
Stopwatch SW = new Stopwatch();
SW.Start();
for (uint i = 0; i < Precision; i++) { Result = Method.Invoke(null, Parameter); }
SW.Stop();
Speed = SW.ElapsedTicks / Precision;
// Reset speed
Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.Normal;
Thread.CurrentThread.Priority = ThreadPriority.Normal;
}
示例3: GetScriptsToRun
public ScriptBlock GetScriptsToRun(object testClass, MethodInfo method)
{
var loadedScripts = LoadScriptsFromAttributes(method);
var scriptBlock = ScriptBlock.Empty.WithDefaultScripts()
.AppendScripts(loadedScripts);
if (IsStringScriptTest(method))
{
var scriptText = (string) method.Invoke(testClass, new object[0]);
scriptBlock = scriptBlock.AppendInlineScript(scriptText);
}
else if (IsScriptBlockTest(method))
{
scriptBlock = (ScriptBlock) method.Invoke(testClass, new[] {scriptBlock});
}
else
{
var scriptFormat = "if (typeof this['{1}'] != 'undefined') {{\r\n" +
" {1}();\r\n" +
"}} else {{\r\n" +
" {0}();\r\n" +
"}}";
var methodNameCamelCase = method.Name.Substring(0, 1).ToLower() + method.Name.Substring(1);
var invocationScript = string.Format(scriptFormat, method.Name, methodNameCamelCase);
scriptBlock = scriptBlock.AppendScript(new FileScriptSource(testClass.GetType().Name + ".js"))
.AppendScript(new InlineScriptSource("test.js", invocationScript));
}
return scriptBlock;
}
示例4: InvokeAction
public Task<ActionResult> InvokeAction(ControllerContext context, MethodInfo action)
{
var parameters = action.GetParameters();
var args = new object[parameters.Length];
for (var i = 0; i < parameters.Length; i++)
{
var key = parameters[i].Name;
object value;
if (context.NavigationContext.Request.QueryString.ContainsKey(key))
value = context.NavigationContext.Request.QueryString[key];
else
value = context.Controller.RouteData[key];
args[i] = value;
}
// If async
if (action.ReturnType == typeof(Task<ActionResult>))
{
return (Task<ActionResult>)action.Invoke(context.Controller, args);
}
// If synchronous
else
{
var actionResult = (ActionResult)action.Invoke(context.Controller, args);
return Task.FromResult(actionResult);
}
}
示例5: Register
/// <summary>
/// Register Request types
/// </summary>
/// <param name="httpConfiguration">HttpConfiguration value</param>
/// <param name="setSampleRequest">SampleRequest MethodInfo value</param>
/// <param name="controllerName">ControllerName value</param>
/// <param name="requestActions">RequestActions value</param>
internal static void Register(HttpConfiguration httpConfiguration, MethodInfo setSampleRequest, string controllerName, IEnumerable<MethodInfo> requestActions, MethodInfo generateObject)
{
try
{
JsonMediaTypeFormatter jsonFormatter = null;
if (httpConfiguration.Formatters != null && httpConfiguration.Formatters.Count > 0)
{
jsonFormatter = httpConfiguration.Formatters.JsonFormatter;
}
foreach (var action in requestActions)
{
if (action.GetParameters().Count() > 0) // Make sure request action is a parameterized action
{
// Documentation output builders
IFluentRequestBuilder jsonSampleBuilder = new JSONSampleBuilder(generateObject, jsonFormatter);
IFluentRequestBuilder xmlSampleBuilder = new XMLSampleBuilder(generateObject);
var actionName = action.Name;
var requestCustomAttribs = Attribute.GetCustomAttributes(action);
foreach (var parameter in action.GetParameters())
{
Type type = parameter.ParameterType;
string parameterName = parameter.Name;
if (requestCustomAttribs != null && requestCustomAttribs.Count() > 0)
{
// Check if the action is decorated with [RequestTypeAttribute] attribute class and if so grab the type from the attribute
var typeQuery = requestCustomAttribs.
Where(rt => rt is RequestTypeAttribute).
Where(p => p.TypeId.ToString().Equals(parameterName));
type = (typeQuery != null && typeQuery.Count() > 0) ?
type = ((RequestTypeAttribute)typeQuery.FirstOrDefault()).Type : type;
}
jsonSampleBuilder = jsonSampleBuilder.BuildSample(type, parameterName);
xmlSampleBuilder = xmlSampleBuilder.BuildSample(type, parameterName);
}
var parameters = action.GetParameters().Select(a => a.Name).ToArray();
setSampleRequest.Invoke(null, new object[] { httpConfiguration, jsonSampleBuilder.Sample, new MediaTypeHeaderValue("text/json"), controllerName, actionName, parameters });
setSampleRequest.Invoke(null, new object[] { httpConfiguration, jsonSampleBuilder.Sample, new MediaTypeHeaderValue("application/json"), controllerName, actionName, parameters });
setSampleRequest.Invoke(null, new object[] { httpConfiguration, xmlSampleBuilder.Sample, new MediaTypeHeaderValue("text/xml"), controllerName, actionName, parameters });
setSampleRequest.Invoke(null, new object[] { httpConfiguration, xmlSampleBuilder.Sample, new MediaTypeHeaderValue("application/xml"), controllerName, actionName, parameters });
}
}
}
catch (Exception exception)
{
throw exception;
}
}
示例6: CreateInvokeDelegate
private void CreateInvokeDelegate(AphidInteropFunctionAttribute attribute, MethodInfo method)
{
var parameters = method.GetParameters();
var paramsParam = parameters
.FirstOrDefault(x => x
.GetCustomAttributes(true)
.Any(y => y is ParamArrayAttribute));
if (paramsParam == null)
{
if (!attribute.PassInterpreter)
{
_invoke = (callerScope, x) => method.Invoke(null, x);
}
else
{
_invoke = (callerScope, x) => method.Invoke(null, PrefixScope(callerScope, x));
}
}
else
{
var paramCount = parameters.Count();
if (attribute.PassInterpreter)
{
paramCount--;
}
_invoke = (callerScope, x) =>
{
object[] parameters2;
if (x.Length < paramCount)
{
parameters2 = new object[x.Length + 1];
Array.Copy(x, parameters2, x.Length);
parameters2[x.Length] = new object[0];
}
else
{
parameters2 = new object[paramCount];
var stdParamCount = paramCount - 1;
Array.Copy(x, parameters2, stdParamCount);
var paramArrayLen = x.Length - stdParamCount;
var paramArray = new object[paramArrayLen];
Array.Copy(x, stdParamCount, paramArray, 0, paramArrayLen);
parameters2[stdParamCount] = paramArray;
}
if (attribute.PassInterpreter)
{
parameters2 = PrefixScope(callerScope, parameters2);
}
return method.Invoke(null, parameters2);
};
}
}
示例7: Invoke
private object Invoke(MethodInfo method, object instance, object param)
{
object result;
var deSerializedParam = GetMethoParam(method, param);
if (deSerializedParam == null)
{
result = method.Invoke(instance, null);
}
else
{
result = method.Invoke(instance, new[] { deSerializedParam });
}
return result;
}
示例8: GenerateInvokeDelegate
internal InvokeDelegate GenerateInvokeDelegate(MethodInfo method, out int inputParameterCount, out int outputParameterCount)
{
ParameterInfo[] parameters = method.GetParameters();
bool returnsValue = method.ReturnType != typeof (void);
var inputCount = parameters.Length;
inputParameterCount = inputCount;
var outputParamPositions = new List<int>();
for (int i = 0; i < inputParameterCount; i++)
{
if (parameters[i].ParameterType.IsByRef)
{
outputParamPositions.Add(i);
}
}
var outputPos = outputParamPositions.ToArray();
outputParameterCount = outputPos.Length;
InvokeDelegate lambda = delegate(object target, object[] inputs, object[] outputs)
{
object[] inputsLocal = null;
if (inputCount > 0)
{
inputsLocal = new object[inputCount];
for (var i = 0; i < inputCount; i++)
{
inputsLocal[i] = inputs[i];
}
}
object result = null;
if (returnsValue)
{
result = method.Invoke(target, inputsLocal);
}
else
{
method.Invoke(target, inputsLocal);
}
for (var i = 0; i < outputPos.Length; i++)
{
outputs[i] = inputs[outputPos[i]];
}
return result;
};
return lambda;
}
示例9: InvokeTargetsMethod
public object InvokeTargetsMethod(MethodInfo getTargetsMethod, IParameters parameters) {
ParameterInfo[] methodParameters = getTargetsMethod.GetParameters();
if (methodParameters.Length == 1) {
if (methodParameters[0].ParameterType.IsAssignableFrom(typeof(IParameters)))
{
return getTargetsMethod.Invoke(null, new[] { parameters });
}
}
if (methodParameters.Length == 0) {
return getTargetsMethod.Invoke(null, new object[0]);
}
throw new TargetsMethodWrongSignatureException(getTargetsMethod.Name);
}
示例10: CreateHandlerForMethod
/// <summary>
/// Converts the given method into an <see cref="ISourcedEventHandler"/> object.
/// </summary>
/// <param name="aggregateRoot">The event source from which we want to invoke the method.</param>
/// <param name="method">The method to invoke</param>
/// <param name="exact"><b>True</b> if we need to have an exact match, otherwise <b>False</b>.</param>
/// <returns>An <see cref="ISourcedEventHandler"/> that handles the execution of the given method.</returns>
private static ISourcedEventHandler CreateHandlerForMethod(IEventSource eventSource, MethodInfo method, bool exact)
{
Type firstParameterType = method.GetParameters().First().ParameterType;
Action<IEvent> handler = e => method.Invoke(eventSource, new object[] { e });
return new TypeThresholdedActionBasedDomainEventHandler(handler, firstParameterType, exact);
}
示例11: CallMethod
private static object CallMethod(MethodInfo methodInfo)
{
if (methodInfo.GetParameters().Length > 0) return null;
var obj = Activator.CreateInstance(methodInfo.DeclaringType);
var ret = methodInfo.Invoke(obj, null);
return ret;
}
示例12: RunTestAsync
private async Task<FeatureTestResult> RunTestAsync(MethodInfo test, Type adapterType, IEnumerable<FeatureTestRun> dependencies) {
var specialCase = this.GetSpecialCase(test, adapterType)
?? this.GetSpecialCase(test.DeclaringType, adapterType);
if (specialCase != null && specialCase.Skip)
return new FeatureTestResult(FeatureTestResultKind.SkippedDueToSpecialCase, specialCase.Comment);
foreach (var dependency in dependencies) {
var result = await dependency.Task;
if (result.Kind != FeatureTestResultKind.Success) {
var className = FeatureTestAttributeHelper.GetDisplayName(dependency.Method.DeclaringType);
var testName = FeatureTestAttributeHelper.GetDisplayName(dependency.Method);
var skippedComment = string.Format("Skipped as {0} ({1}) is not supported by this library.", testName, className);
return new FeatureTestResult(FeatureTestResultKind.SkippedDueToDependency, skippedComment);
}
}
var instance = Activator.CreateInstance(test.DeclaringType);
using (instance as IDisposable) {
try {
await Task.Run(() => test.Invoke(instance, new object[] {LibraryProvider.CreateAdapter(adapterType)}));
}
catch (Exception ex) {
var useful = ToUsefulException(ex);
if (useful is SkipException)
return new FeatureTestResult(FeatureTestResultKind.SkippedDueToSpecialCase, useful.Message);
return new FeatureTestResult(FeatureTestResultKind.Failure, exception: useful);
}
}
var comment = specialCase != null ? specialCase.Comment : null;
return new FeatureTestResult(FeatureTestResultKind.Success, comment);
}
示例13: InvokeMethod
private static object InvokeMethod(MethodInfo methodInfo, object instance, object[] arguments)
{
try
{
return methodInfo.Invoke(instance, arguments);
}
catch (ArgumentException ex)
{
throw new JobPerformanceException(
"An exception occurred during performance of the job.",
ex);
}
catch (TargetInvocationException ex)
{
if (ex.InnerException is OperationCanceledException && !(ex.InnerException is TaskCanceledException))
{
// `OperationCanceledException` and its descendants are used
// to notify a worker that job performance was canceled,
// so we should not wrap this exception and throw it as-is.
throw ex.InnerException;
}
throw new JobPerformanceException(
"An exception occurred during performance of the job.",
ex.InnerException);
}
}
示例14: ChangeStates
private static void ChangeStates(UnityObject target, MethodInfo restoreState, MethodInfo saveState) {
object result = restoreState.Invoke(null, new object[] { target });
if ((bool)result == false) {
Debug.LogWarning("Skipping " + target + " -- unable to successfuly deserialize", target);
return;
}
ISerializedObject serializedObj = (ISerializedObject)target;
var savedKeys = new List<string>(serializedObj.SerializedStateKeys);
var savedValues = new List<string>(serializedObj.SerializedStateValues);
var savedRefs = new List<UnityObject>(serializedObj.SerializedObjectReferences);
result = saveState.Invoke(null, new object[] { target });
if ((bool)result == false) {
Debug.LogWarning("Skipping " + target + " -- unable to successfuly serialize", target);
serializedObj.SerializedStateKeys = savedKeys;
serializedObj.SerializedStateValues = savedValues;
serializedObj.SerializedObjectReferences = savedRefs;
return;
}
Debug.Log("Successfully migrated " + target, target);
EditorUtility.SetDirty(target);
}
示例15: Create
private ServiceEntry Create(string serviceId, MethodInfo method)
{
var type = method.DeclaringType;
return new ServiceEntry
{
Descriptor = new ServiceDescriptor
{
Id = serviceId
},
Func = parameters =>
{
var instance = _serviceFactory.Create(type);
var list = new List<object>();
foreach (var parameterInfo in method.GetParameters())
{
var value = parameters[parameterInfo.Name];
list.Add(Convert.ChangeType(value, parameterInfo.ParameterType));
}
return method.Invoke(instance, list.ToArray());
}
};
}