zoukankan      html  css  js  c++  java
  • sealed关键字

    1. sealed关键字
        当对一个类应用 sealed 修饰符时,此修饰符会阻止其他类从该类继承。类似于Java中final关键字。
        在下面的示例中,类 B 从类 A 继承,但是任何类都不能从类 B 继承。
    2. sealed 修饰方法或属性
        能够允许类从基类继承,并防止它们重写特定的虚方法或虚属性。
        1)sealed是对虚方法或虚属性,也就是同override一起使用,如果不是虚方法或虚属性会报出错误:cannot be sealed because it is not an override

    public class D  
    {  
        /* ConsoleApplication1.MSFun.Sealed.D.M()'   
         * cannot be sealed because it is not an override   
         */  
        public sealed void M() { Console.WriteLine("D.M()"); }  
    }  
    View Code

        2)防止子类重写特定的方法或属性

    public class A  
    {  
        protected virtual void M() { Console.WriteLine("A.M()"); }  
        protected virtual void M1() { Console.WriteLine("A.M1()"); }  
    }  
      
    public class B : A  
    {  
        protected sealed override void M() { Console.WriteLine("B.M()"); }  
        protected override void M1() { Console.WriteLine("B.M1()"); }  
    }  
      
    public sealed class C : B  
    {  
        /* ConsoleApplication1.MSFun.Sealed.C.M()': 
         * cannot override inherited member 'ConsoleApplication1.MSFun.Sealed.B.M()' 
         * because it is sealed */  
        //protected override void M() { Console.WriteLine("C.M()"); }  
      
        protected override void M1() { Console.WriteLine("C.M1()"); }  
    }  
    View Code
  • 相关阅读:
    c++ 队列
    17:特殊类成员:函数指针5
    c++ deque 双端队列
    18:字符串-char型字符串
    c++ 16 this 和 继承 及继承机制中的构造函数 与 析构函数
    c++ string char* const char*
    c++ 小片段
    google protobuf 使用示例
    hibernate-cache
    hibernate-criteria查询(二)
  • 原文地址:https://www.cnblogs.com/scmail81/p/8605523.html
Copyright © 2011-2022 走看看