Skip to content

Instantly share code, notes, and snippets.

@manisero
Last active September 14, 2018 18:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save manisero/84e8a72dadc8595b33a85ef7dfc379db to your computer and use it in GitHub Desktop.
Save manisero/84e8a72dadc8595b33a85ef7dfc379db to your computer and use it in GitHub Desktop.
Extension methods enabling convenient generic methods invocation through reflection.
// using System;
// using System.Reflection;
// using System.Runtime.ExceptionServices;
[System.Diagnostics.DebuggerStepThrough]
public static void InvokeAsGeneric(
this MethodInfo method,
object target,
Type[] typeArguments,
params object[] arguments)
=> method.InvokeAsGeneric<object>(target, typeArguments, arguments);
[System.Diagnostics.DebuggerStepThrough]
public static TResult InvokeAsGeneric<TResult>(
this MethodInfo method,
object target,
Type[] typeArguments,
params object[] arguments)
{
try
{
return (TResult)method.MakeGenericMethod(typeArguments)
.Invoke(target, arguments);
}
catch (TargetInvocationException exception)
{
ExceptionDispatchInfo.Capture(exception.InnerException).Throw();
throw;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment