c# - 如何摆脱虚拟表?密封类

标签 c# oop inheritance vtable sealed

据我所知,使类 sealed 摆脱了在 VTable 中的查找,或者我错了吗?如果我创建一个类 sealed,这是否意味着类层次结构中的所有虚方法也都标记为 sealed

例如:

public class A {
    protected virtual void M() { ........ }
    protected virtual void O() { ........ }
}

public sealed class B : A {
    // I guess I can make this private for sealed class
    private override void M() { ........ }
    // Is this method automatically sealed? In the meaning that it doesn't have to look in VTable and can be called directly?

    // Also what about O() can it be called directly too, without VTable?
}

最佳答案

"I guess I can make this private for sealed class"

您不能更改继承层次结构中的访问修饰符。这意味着如果基类中的方法是 public,则不能在派生类中将其设为 privateinternalprotected类。仅当将方法声明为 new 时才能更改修饰符:

private new void M() { ........ }

As far as I know making class sealed gets rid of look up in VTable or am I wrong?

密封类在层次结构中排在最后,因为您不能从它继承。虚拟表可以与 sealed 类一起使用,以防此 sealed 类覆盖基类中的某些方法。

If I make a class sealed does this mean that all virtual methods in class hierarchy are also marked sealed?

可以看到IL代码:

.method family hidebysig virtual            // method is not marked as sealed
    instance void M () cil managed 
{        
    .maxstack 8

    IL_0000: nop 
    IL_0001: ret value
}  

方法未标记为密封。即使您将此方法显式标记为 sealed,您也会获得相同的 IL 代码。

此外,没有理由在sealed 类中将方法标记为sealed。如果类是密封的,那么您就无法继承它,也无法继承它的方法。

关于虚拟表 - 如果方法被覆盖并且您从虚拟表中删除它,您永远不能在继承层次结构中使用它,因此没有理由覆盖方法并且永远不要在继承层次结构中使用它。

关于c# - 如何摆脱虚拟表?密封类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42505773/

相关文章:

c++ - 从专门的模板结构/类继承

c# - SharedAssemblyInfo.cs

javascript - 如何在内存中没有字符串的情况下将用户密码从 HTML 表单获取到服务器端 SecureString

java - 代号一 SQLite 数据问题

java - 我应该使用哪种设计模式?

scala - 为什么可以在 Scala 中实例化多个特征,但不能实例化一个?

c# - .net 在本地主机和 azure 网站之间输出不同的日期格式

c# - Nest 5.6 - 如何插入已存在 id 的文档?

c++ - 使类构造函数私有(private)

java - java接口(interface)与继承