c# 封装sealed修饰符

使用sealed修饰的类,标识封装类,不能被继承,如class b 不能被其他类继承;

class A {}
sealed class B : A {}

也能用sealed修饰重写的虚方法或属性,如下所示,Y类重写了X类的虚方法,并用sealed修饰F方法,那么,Z类就无法重写F方法,所以可以阻止后代重写sealed修饰的方法和属性;

class X
{
protected virtual void F() { Console.WriteLine("X.F"); }
protected virtual void F2() { Console.WriteLine("X.F2"); }
}

class Y : X
{
sealed protected override void F() { Console.WriteLine("Y.F"); }
protected override void F2() { Console.WriteLine("Y.F2"); }
}

class Z : Y
{
// Attempting to override F causes compiler error CS0239.
// protected override void F() { Console.WriteLine("Z.F"); }

// Overriding F2 is allowed.
protected override void F2() { Console.WriteLine("Z.F2"); }
}

posted @ 2023-05-12 16:37  路鸣  阅读(61)  评论(0编辑  收藏  举报