实现带两参数函数时抛出“Exception has been thrown by the target of an invocation”异常
Hey there, let's break down this issue you're hitting with dynamically generated multi-parameter methods implementing interfaces. That "Exception has been thrown by the target of an invocation" error is almost always a wrapper for the real underlying problem—so first, we need to unwrap it to see what's actually going wrong.
First things first, add a try-catch block around where you invoke the dynamically generated method, and dig into the InnerException—that's where the actual error message lives:
try { // Call your dynamically generated method here } catch (System.Reflection.TargetInvocationException ex) { // This is the critical info you're missing Console.WriteLine($"Actual Error: {ex.InnerException.Message}"); Console.WriteLine($"Stack Trace: {ex.InnerException.StackTrace}"); }
The inner exception will tell you exactly what's broken—like type mismatches, missing parameters, or invalid expression tree logic.
Based on typical dynamic method generation issues, here are the most likely culprits:
- Parameter Type Mismatch: The types of parameters you define in your expression tree don't exactly match the interface method's parameter types. For example, if the interface expects
intbut your dynamic method useslong, or you mix up nullable vs non-nullable types. - Wrong Parameter Order: When building your expression tree, you've swapped the order of parameters compared to the interface method. If the interface method is
void Process(int id, string name), but you bind the string parameter first, invoking it will throw a type mismatch error. - Unbound Parameters: For multi-parameter methods, you might have forgotten to include one or more parameters in your method body expression. For example, when building a
MethodCallExpression, you didn't pass all required parameter expressions to the call. - Return Type Mismatch: If the interface method has a return value, your dynamic method's return type doesn't align with what the interface expects.
Since your code was cut off, here are specific checks to run against your dynamic generation logic:
- Verify Parameter Definitions:
When creatingExpression.Parameterinstances for your method, make sure each parameter'sTypeexactly matches the corresponding parameter in the interface method. UseinterfaceMethod.GetParameters()to pull the exact types instead of hardcoding them. - Check Method Body Construction:
If you're building a method call or custom logic, ensure you pass all parameter expressions to the body in the correct order. For example:var interfaceMethod = typeof(IMyInterface).GetMethod("TwoParamMethod"); // Pull exact parameter types from the interface var parameters = interfaceMethod.GetParameters() .Select(p => Expression.Parameter(p.ParameterType, p.Name)) .ToArray(); // Build method body that uses all parameters (or valid logic) var body = Expression.Add(parameters[0], parameters[1]); // Example logic // Create lambda with ALL parameters var lambda = Expression.Lambda(interfaceMethod.ReturnType, body, parameters); var dynamicMethod = lambda.Compile(); - Validate Delegate/Lambda Signature:
When usingExpression.LambdaorMethodBuilder, the signature (parameter count, types, return type) must match the interface method exactly. Even a tiny mismatch (likeintvsint?) will trigger the target invocation exception.
内容的提问来源于stack exchange,提问作者StartCoding

