Last active
September 14, 2018 18:04
-
-
Save manisero/84e8a72dadc8595b33a85ef7dfc379db to your computer and use it in GitHub Desktop.
Extension methods enabling convenient generic methods invocation through reflection.
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
// 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