C#从另一个接口覆盖接口方法
假设我有接口
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您要覆盖方法时,您不能更改签名,因此
getValue(bool)
会产生超载,而不是覆盖(该方法具有默认参数并没有区别)。 但是您的iCachedRepository
dim enasalgetValue()
在继承了基本接口。当您为接口编写实现时,必须指定这两种方法:
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 yourICachedRepository
does implementGetValue()
as you inherit the base interface.When you write an implementation for your interface, you have to specify both methods:
The
GetValue()
method is part ofICachedRepository
, even though you don't declare an override in it inICachedRepository
. 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 callingGetValue()
andGetValue(false)
perform the same operation.