C# sealed 方法
sealed是用来中断继承链的。
sealed 能让一个类失去被继承的能力。
public class SubClass : BaseInterClass { public override void absfunction() { base.absfunction(); Console.WriteLine("beside baseclass ovveride absfunction output, sub class override absfunction!!!"); } } sealed class subsubClass : SubClass { } class subsubsubClass : SubClass { }
sealed用在方法上就是 到当前类为止,所有继承当前类的子类都无法再override这个方法了。
- virtual / abstract 类型的方法必须是public的。
- abstract类型的方法只能定义在abstract类中,virtual类型的方法无限制。
- 只有virtual / abstract 类型的方法才能被override.
- virtual 类型的方法可以有具体实现。
- abstract 类型的方法不可以有具体实现,只能有定义。
public abstract class AbstractClass{ static void show() { Console.WriteLine("abstractor class show function !!!"); } public virtual void hello() { Console.WriteLine("abs class hello function !!!"); } public abstract void absfunction(); public void normalfunction() { Console.WriteLine("abs class normal function!!!"); } } public class BaseInterClass : AbstractClass { public sealed override void hello() { Console.WriteLine("abs class sealed hello function,avoid be overitten!!!!"); } public override void absfunction() { Console.WriteLine("BaseInterClass override function!!!"); } } public class SubClass : BaseInterClass { public override void absfunction() { base.absfunction(); Console.WriteLine("beside baseclass ovveride absfunction output, sub class override absfunction!!!"); } } 调用: BaseInterClass b1 = new BaseInterClass(); b1.normalfunction(); b1.hello(); SubClass b2 = new SubClass(); b2.hello(); b2.absfunction(); 输出: base class normal function!!! abs class normal function!!! abs class sealed hello function,avoid be overitten!!!! abs class sealed hello function,avoid be overitten!!!! BaseInterClass override function!!! beside baseclass ovveride absfunction output, sub class override absfunction!!!