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

C#中继承接口能否为父接口方法提供默认实现?

继承接口能否为父接口方法提供默认实现?

你从Swift转C#后使用接口默认实现时遇到的问题,核心解决思路是子接口需要用new关键字明确声明要覆盖父接口的同名方法,这样既可以消除CS0108警告,也能让默认实现真正生效,避免子类被迫重复实现方法。

问题根源

C#中,子接口定义与父接口同名的成员时,默认会被视为“隐藏”父接口成员,编译器会抛出CS0108警告提示你确认意图。如果不加new,子接口的Checkout其实和父接口的Checkout是两个独立成员,所以实现类依然需要满足父接口的要求,必须实现Checkout。

解决方案:添加new关键字

在子接口的Checkout方法前加上new,明确告知编译器你是有意用子接口的默认实现覆盖父接口的声明,这样默认实现会绑定到子接口,实现类无需再重复实现该方法。

修改后的代码示例:

using UnityEngine; // 若未使用Unity,可替换为Console.WriteLine

interface IProduct {
    string name { get; }
    void Checkout();
}

interface IPhysicalProduct : IProduct
{
    void ShipItem() { Debug.Log("Shipping item"); }
    public new void Checkout() { ShipItem(); } // 添加new关键字消除警告并启用默认实现
}

interface IDigitalProduct: IProduct
{
    int totalDownloadsLeft { get; }
    void DownloadItem() { Debug.Log($"Downloading item; {totalDownloadsLeft} downloads left"); }
    public new void Checkout() { DownloadItem(); } // 同理添加new
}

class PhysicalProd : IPhysicalProduct
{
    public string name => "实体商品";
    // 无需再手动实现Checkout,会自动使用IPhysicalProduct的默认实现
}

// 测试验证
class Program
{
    static void Main()
    {
        PhysicalProd prod = new PhysicalProd();
        prod.Checkout(); // 输出:Shipping item

        // 注意:父接口类型引用需要显式转换才能调用子接口的默认实现
        IProduct product = prod;
        ((IPhysicalProduct)product).Checkout(); // 正常输出
    }
}

注意事项

当用父接口(IProduct)类型引用实现类对象时,直接调用Checkout会编译失败,因为父接口本身没有默认实现。必须显式转换为子接口类型(IPhysicalProduct/IDigitalProduct),才能触发对应的默认实现逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 20:03:28