据我所知,使类 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
,则不能在派生类中将其设为 private
或 internal
或 protected
类。仅当将方法声明为 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/