我遵循本指南https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/default-interface-methods使用默认接口实现功能。我复制了一个代码,该代码定义了接口IA
中的默认实现,然后在接口IB
:中重写它
interface I0
{
void M() { Console.WriteLine("I0"); }
}
interface I1 : I0
{
override void M() { Console.WriteLine("I1"); }
}
但它给出了一个错误CS0106 The modifier 'override' is not valid for this item
和一个警告CS0108 'I1.M()' hides inherited member 'I0.M()'. Use the new keyword if hiding was intended
。TargetFramework
被设置为net5.0
,LangVersion
被设置为latest
。为什么即使在官方文件中有描述,它也不起作用?
显然,带有override
关键字的示例不正确,必须删除此关键字。此外,只有当显式指定方法接口时,它才起作用:
interface I0
{
void M() { Console.WriteLine("I0"); }
}
interface I1 : I0
{
void I0.M() { Console.WriteLine("I1"); }
}
在文本中,它说"不允许隐式重写">
令人困惑的是,它后面的IC
接口在使用隐式方法时没有重复该语句,使其看起来隐式方法是有效的。IC
似乎就是您复制的接口。