首页 > 编程语言 >c# 封装sealed修饰符

c# 封装sealed修饰符

时间:2023-05-12 16:45:29浏览次数:37  
标签:F2 Console sealed c# void 修饰符 WriteLine class

使用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"); }
}

标签:F2,Console,sealed,c#,void,修饰符,WriteLine,class
From: https://www.cnblogs.com/lumingprince/p/17395091.html

相关文章