C#内联方法会在接口中声明吗? [英] Will C# inline methods that are declared in interfaces?

查看:106
本文介绍了C#内联方法会在接口中声明吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个界面:

 interface IMyInterface
 {
    void DoSomething();
 }

一个实施类:

 class MyClass : IMyInterface
 {
     public void DoSomething()
     {

     }
 }

DoSomething是内联的候选人吗?我期望不,因为如果它是一个接口,那么该对象可以被转换为IMyInterface,因此被调用的实际方法是未知的。但是事实上它没有标记为虚拟意味着它可能不在vtable上,所以如果对象被转换为MyClass,那么也许它可以被内联?

Is DoSomething a candidate for inlining? I'd expect "no" because if it's an interface then the object may be cast as a IMyInterface, so the actual method being called is unknown. But then the fact that it's not marked as virtual implies it may not be on the vtable, so if the object is cast as MyClass, then maybe it could be inlined?

推荐答案

如果直接调用 DoSomething ,那么它将成为内联的候选者(取决于该方法是否符合与大小相关的其他内联标准等等)。

If you call DoSomething directly then it will be a candidate for inlining (depending on whether the method meets the other inlining criteria relating to size etc).

如果您通过界面拨打 DoSomething ,则不会内联。接口提供的间接导致需要vtable查找的虚拟调用,因此JIT编译器无法内联它,因为实际的调用点仅在运行时解析。

If you call DoSomething via the interface then it will not be inlined. The indirection provided by the interface results in a virtual call requiring a vtable lookup so the JIT compiler is unable to inline it since the actual callsite is only resolved at runtime.

这篇关于C#内联方法会在接口中声明吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆