加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 为什么可以从同一方法的覆盖版本调用方法的基本版本

发布时间:2020-12-16 00:11:00 所属栏目:百科 来源:网络整理
导读:我很困惑为什么C#让我这样做: 基类 public virtual void OnResultExecuted(ResultExecutedContext filterContext){} 派生类 public override void OnResultExecuted(ResultExecutedContext filterContext){ base.OnResultExecuted(filterContext);} 这段代
我很困惑为什么C#让我这样做:

基类

public virtual void OnResultExecuted(ResultExecutedContext filterContext)
{

}

派生类

public override void OnResultExecuted(ResultExecutedContext filterContext)
{
    base.OnResultExecuted(filterContext);
}

这段代码没有问题.但它是如何调用base.OnResult当这是我重写的方法时执行了?

解决方法

为什么这很有用是非常明显的. “怎么样?”不太明显,但也很有趣.

存储.NET代码的MSIL编码有两个方法调用指令:

>打电话
> callvirt

不同之处在于,当callvirt与虚方法一起使用时,它不会调用指示的方法.相反,它将指示的方法映射到对象类的vtable中的一个槽,找到属于该对象类的实际实现,并调用该版本.

(对于非虚方法,callvirt只是添加一个空检查,然后直接调用指定的方法).

调用指令不使用vtable.它只是调用MSIL中指定的方法.在C#中使用base关键字时,编译器会生成一个调用指令,以便使用基类提供的确切方法,而不是vtable中链接的重写方法.

此行为是documented on MSDN for the call opcode

It is valid to call a virtual method using call (rather than callvirt); this indicates that the method is to be resolved using the class specified by method rather than as specified dynamically from the object being invoked.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读