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

在接口中指定返回值为继承该接口的类类型及实现代码

实现方案

你需要的是**奇异递归模板模式(CRTP)**的典型使用场景,可通过泛型接口+类型约束实现,以下是常用语言的可运行代码:

C# 实现(对应你给出的语法框架)

// 定义泛型接口,约束泛型参数必须是实现该接口的类型
public interface IExample<out T> where T : IExample<T>
{
    T ReturnMe();
}

// 实现类将自身作为泛型参数传入接口
public class Example : IExample<Example>
{
    public Example ReturnMe()
    {
        // 返回当前类实例即可
        return this;
    }
}

注:如果不需要协变场景,接口定义可以去掉out关键字,写成public interface IExample<T> where T : IExample<T>即可。

测试验证

var instance = new Example();
var result = instance.ReturnMe();
// 输出True,验证返回值确实为Example类实例
Console.WriteLine(result is Example);

Java 实现

// 泛型接口定义
public interface IExample<T extends IExample<T>> {
    T returnMe();
}

// 实现类
public class Example implements IExample<Example> {
    @Override
    public Example returnMe() {
        return this;
    }
}

C++ 实现

template <typename T>
class IExample {
public:
    T* ReturnMe() {
        return static_cast<T*>(this);
    }
    virtual ~IExample() = default;
};

class Example : public IExample<Example> {};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 16:54:03