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

如何为C#隐式转换运算符添加额外的泛型参数TRES

错误根因

C# 语言规范不允许自定义的隐式/显式转换运算符声明自己专属的泛型参数,只能使用其所属类型已经定义的泛型参数。
你写的第一个转换运算符仅用到了State<T>类定义的泛型参数T,符合语法要求可以正常编译;第二个转换运算符额外声明了独有的泛型参数TRES,不符合语法规则,因此报错。而普通成员方法允许声明自身的泛型参数,所以对应的Updater<TRES>方法可以正常编译。

替代实现方案

方案1:直接复用已有的泛型Use方法(最简便,推荐)

你已经实现了泛型版本的Use<TRES>方法,本身已经完全满足「传入带返回值的FuncRef修改状态并拿到返回值」的需求,不需要额外做隐式转换,直接调用即可:

// 调用示例
State<int> state = new 你的State实现类();
int result = state.Use((ref int val) => {
    val += 10;
    return val;
});

方案2:通过中间代理类实现类似隐式转换的效果

如果你确实需要支持「将State实例直接赋值给对应泛型Func类型变量」的能力,可以新增一个中间代理类中转,调整代码如下:

// 新增中间代理类
public class StateFuncWrapper<T>
{
    private readonly State<T> _state;
    public StateFuncWrapper(State<T> state) => _state = state;

    // 代理类提供对应泛型Func的隐式转换
    public static implicit operator Func<FuncRef<T, TRes>, TRes><TRes>(StateFuncWrapper<T> wrapper)
    {
        return f => wrapper._state.Use(f);
    }
}

abstract public class State<T>
{
    T Value; // internal state 

    public virtual void Use(ActionRef<T> f)
    {
        // code that modifies the state
    }

    public virtual TRes Use<TRes>(FuncRef<T, TRes> f)
    {
        // code that modifies the state and returns a value
        return default;
    }

    public static implicit operator Action<ActionRef<T>>(State<T> instance)
    {
        return f => instance.Use(f);
    }

    // 新增到中间代理类的隐式转换
    public static implicit operator StateFuncWrapper<T>(State<T> instance)
    {
        return new StateFuncWrapper<T>(instance);
    }
}

// 调用示例
State<int> myState = new 你的State实现类();
Func<FuncRef<int, int>, int> updater = myState;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 02:54:05