C#从另一个接口覆盖接口方法

发布于 2025-02-08 23:13:33 字数 509 浏览 3 评论 0原文

假设我有接口

public interface IRepository
{
    string GetValue();
}

,然后我需要扩展此接口,以便它支持

public interface ICachedRepository: IRepository
{
    void SetCache(string value);

    string GetValue(bool ignoreCache = false);
}

您所看到的缓存,我想覆盖getValue方法,以便它具有ignorecache参数。但是看起来我超载方法,而不是覆盖它。是否有任何方法可以完全覆盖getValue,因此实现ICACHEDREPOSITOR的类无需从irepository实现getValue代码>?

Let's say I have interface

public interface IRepository
{
    string GetValue();
}

And then I need to extend this interface so it supports cache

public interface ICachedRepository: IRepository
{
    void SetCache(string value);

    string GetValue(bool ignoreCache = false);
}

As you can see, I want to override GetValue method so that it has ignoreCache argument. But it looks like I overload method, instead of overriding it. Is there any way to fully override GetValue, so that class that implements ICachedRepository won't need to implement GetValue from IRepository ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

贱人配狗天长地久 2025-02-15 23:13:33

当您要覆盖方法时,您不能更改签名,因此getValue(bool)会产生超载,而不是覆盖(该方法具有默认参数并没有区别)。 但是您的iCachedRepository dim enasal getValue()在继承了基本接口。

当您为接口编写实现时,必须指定这两种方法:

public class RepositoryImplementation : ICachedRepository
{
    public string GetValue() { GetValue(false) }
    public string GetValue(bool ignoreCache) { ... }
    public void SetCache(string value) {...}
}

getValue()方法是iCachedRepository的一部分,即使您没有在In In In中声明覆盖它在iCachedrepository中。实际上,在接口中宣布覆盖效率是非法的。

旁注:我将从getValue(bool ignorecache = false)删除默认参数规范,因为当没有参数的另一个过载时,它会混淆。而是确保调用getValue()getValue(false)执行相同的操作。

You can't change the signature when you want to override a method, therefore GetValue(bool) creates an overload, not an override (that the method has a default argument doesn't make a difference). But your ICachedRepository does implement GetValue() as you inherit the base interface.

When you write an implementation for your interface, you have to specify both methods:

public class RepositoryImplementation : ICachedRepository
{
    public string GetValue() { GetValue(false) }
    public string GetValue(bool ignoreCache) { ... }
    public void SetCache(string value) {...}
}

The GetValue() method is part of ICachedRepository, even though you don't declare an override in it in ICachedRepository. It's actually illegal to declare overrides in interfaces.

Side note: I would remove the default parameter specification from GetValue(bool ignoreCache = false) because it's confusing when another overload without the parameter exists. Instead, make sure that calling GetValue() and GetValue(false) perform the same operation.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文