在学习C#中一些较新的语言功能时,我注意到您可以在接口的非静态方法定义中添加abstract
和virtual
,但我很难理解其用途.
下面是一个例子:
public interface IFoo
{
// Is there any functional difference between these two?
abstract string AbstractInstanceMethod();
string InstanceMethod();
// Or these two?
virtual string VirtualInstanceMethod() => "bar";
string InstanceMethodWithDefaultImplementation() => "bar";
}
我可以看到,对于关键字virtual
,您必须提供实现,而对于关键字abstract
,您不能提供实现.但这些限制似乎只出现在当前接口上的定义中,所以我不妨 Select 提供一个实现或 Select 不提供一个实现.
在派生接口中,您可以使用关键字new
覆盖上面的任何实现,然后在abstract
、virtual
或默认实现中自由 Select ,而不考虑原始定义.
我还试图通过创建具有不同程度的覆盖/实现的派生类,然后调用它们来查看执行了哪些方法体,从而梳理出任何差异,但它总是与变量定义中使用的类型相匹配.
It seems like the keywords just allow you to be more explicit, but I can't find any documentation that confirms this. Can anyone help with this?个
If the keywords are redundant, does anyone know of any Roslyn rules to disallow them? I like to avoid having two ways to write the same thing.
PS-抱歉,如果这是一个愚弄或只是一点文件,我错过了.我发现搜索很困难,因为所有关键字的含义都过载了.