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

FluentResult:如何用单个方法返回Result.Fail处理泛型与非泛型Result

统一处理FluentResult泛型与非泛型结果的单方法实现

要实现单个泛型方法同时处理Result(非泛型)和Result<T>(泛型),核心是解决不同结果类型的实例创建问题——因为FluentResult的Result和Result<T>均继承自ResultBase,但直接返回基类实例无法匹配泛型约束的具体类型。

解决方案代码

using FluentResults;
using System.Reflection;

public TRes Check<TRes>(TRes input) where TRes : ResultBase
{
    // 成功状态直接返回原结果
    if (!input.IsFailed)
        return input;

    var resType = typeof(TRes);

    // 处理非泛型Result
    if (resType == typeof(Result))
    {
        return (TRes)(object)Result.Fail("统一错误消息");
    }

    // 处理泛型Result<T>
    if (resType.IsGenericType && resType.GetGenericTypeDefinition() == typeof(Result<>))
    {
        var valueType = resType.GetGenericArguments()[0];
        // 反射调用对应泛型的Fail方法
        var failMethod = typeof(Result)
            .GetMethod(nameof(Result.Fail), new[] { typeof(string) })
            .MakeGenericMethod(valueType);
        var newFailedResult = failMethod.Invoke(null, new object[] { "统一错误消息" });
        
        return (TRes)newFailedResult;
    }

    // 自定义ResultBase子类的 fallback 处理
    return input;
}

关键逻辑说明

  1. 类型判断:通过typeof(TRes)区分非泛型Result和泛型Result<T>,避免编写重载方法。
  2. 反射创建实例:针对泛型Result<T>,利用反射获取并调用Result.Fail<T>静态方法,生成与TRes匹配的失败结果实例。
  3. 类型转换:通过(TRes)(object)的装箱/拆箱操作,绕过编译期类型检查(运行时已确认类型匹配)。

扩展调整

如果你的统一处理不是修改错误消息,而是其他逻辑(比如添加通用错误、记录日志),只需调整创建失败实例的逻辑即可。例如,保留原错误并追加新消息:

// 针对非泛型Result
return (TRes)(object)Result.Fail(input.Errors).WithMessage("统一追加消息");

// 针对泛型Result<T>
var existingErrors = input.Errors;
var failMethod = typeof(Result)
    .GetMethod(nameof(Result.Fail), new[] { typeof(IEnumerable<IError>) })
    .MakeGenericMethod(valueType);
var newFailedResult = failMethod.Invoke(null, new object[] { existingErrors }) as ResultBase;
newFailedResult = newFailedResult.WithMessage("统一追加消息");
return (TRes)newFailedResult;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 11:50:14