当前位置: 网站首页 > .NET > c#

实现Interface的函数总是虚函数么?

时间:1970-1-1 08:33:31来源: c#作者:admin 点击:0次 字体 [ С]

    以下这段代码有编译错误:

public interface IExample
{
void ShowExampe(string example);
}
public class DetailedExample : IExample
{
public void ShowExampe(string example) //Line 7
{
//implementation detail
}
}
public class BlogDetailedExample : DetailedExample
{
public override void ShowExampe(string example) //Line 14
{
//My override
}
}

    错误代码是CS0506: \\\\\\\'function1\\\\\\\' : cannot override inherited member \\\\\\\'function2\\\\\\\' because it is not marked "virtual", "abstract", or "override"。从此我们也许可以推断出第七行的ShowExample不是虚函数。实际上,它是虚函数,至少从IL代码可以看到virtual的标记:
method public hidebysig newslot virtual final instance void ShowExampe(string example) cil managed

    但是我们注意到了final的使用,这使得此虚函数不可以再被override. 现在将第七行改成 public virtual void ShowExampe(string example) 则可以使得代码编译通过。此时其IL就和类自己定义的(而不是通过实现interface得到的)虚函数一样了:

发表评论
验证码:
最新评论