You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

实现带两参数函数时抛出“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.

Step 1: Capture the Real Exception

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.

Common Multi-Parameter Pitfalls

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 int but your dynamic method uses long, 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.
Troubleshooting Your Code (Even With the Truncated Snippet)

Since your code was cut off, here are specific checks to run against your dynamic generation logic:

  1. Verify Parameter Definitions:
    When creating Expression.Parameter instances for your method, make sure each parameter's Type exactly matches the corresponding parameter in the interface method. Use interfaceMethod.GetParameters() to pull the exact types instead of hardcoding them.
  2. 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();
    
  3. Validate Delegate/Lambda Signature:
    When using Expression.Lambda or MethodBuilder, the signature (parameter count, types, return type) must match the interface method exactly. Even a tiny mismatch (like int vs int?) will trigger the target invocation exception.

内容的提问来源于stack exchange,提问作者StartCoding

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:49:58