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

C#中使用泛型执行助手函数调用带out参数函数编译失败问题

解决带out参数的泛型执行助手函数编译错误

问题根源是**.NET内置的Func<...>委托不支持out参数**,你需要自定义一个符合函数签名的委托类型来替代它。

步骤1:定义支持out参数的自定义委托

添加一个泛型委托,匹配你的目标函数签名(输入TIn1、out TIn2参数,返回int):

public delegate int OutFunc<in TIn1, out TIn2>(TIn1 input, out TIn2 output);

步骤2:修改ExecutionHelper方法的参数类型

把原来的Func<TIn1, out TIn2, int>替换为自定义的OutFunc<TIn1, TIn2>:

public class ExecutionUtility
{
    public static TIn2 ExecutionHelper<TIn1, TIn2>(OutFunc<TIn1, TIn2> function, TIn1 input)
    {
        TIn2 output = default(TIn2);
        int result = function(input, out output);

        if (result == 0)
        {
            return output;
        }
        else
        {
            throw new FunctionExecutionException(result);
        }
    }
}

步骤3:验证调用代码

你的现有调用代码不需要修改,因为myfunction的签名和OutFunc<int, string>完全兼容:

return ExecutionUtility.ExecutionHelper<int, string>(PRD_GCAPI.myfunction, this.Index);

完整可编译代码示例

// 自定义委托
public delegate int OutFunc<in TIn1, out TIn2>(TIn1 input, out TIn2 output);

// 异常类
public class FunctionExecutionException : Exception
{
    public int ErrorCode { get; }

    public FunctionExecutionException(int errorCode)
    : base($"Function execution failed with error code: {errorCode}")
    {
        ErrorCode = errorCode;
    }
}

// 执行工具类
public class ExecutionUtility
{
    public static TIn2 ExecutionHelper<TIn1, TIn2>(OutFunc<TIn1, TIn2> function, TIn1 input)
    {
        TIn2 output = default(TIn2);
        int result = function(input, out output);

        if (result == 0)
        {
            return output;
        }
        else
        {
            throw new FunctionExecutionException(result);
        }
    }
}

// 示例目标函数
public static class PRD_GCAPI
{
    public static int myfunction(int input, out string output)
    {
        if (input > 0)
        {
            output = "OUTPUT_VALUE_1";
            return 0;
        }
        else
        {
            output = "OUTPUT_VALUE_2";
            return -1;
        }
    }
}

// 调用示例
public class SampleUsage
{
    public int Index { get; set; }

    public string Execute()
    {
        return ExecutionUtility.ExecutionHelper<int, string>(PRD_GCAPI.myfunction, this.Index);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 04:22:27