Sealed method in C#

后端 未结 7 1683
萌比男神i
萌比男神i 2020-12-13 13:15

I am a newbie in C#.I am reading about Sealed keyword.I have got about sealed class.I have read a line about Sealed method where we can make Sealed method also.The line was

7条回答
  •  暖寄归人
    2020-12-13 13:23

    Sealed Methods

    Sealed method is used to define the overriding level of a virtual method.

    Sealed keyword is always used with override keyword.

    Practical demonstration of sealed method

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace sealed_method
    {
        class Program
        {
            public class BaseClass
            {
    
                public virtual void Display()
                {
                    Console.WriteLine("Virtual method");
                }
            }
    
           public class DerivedClass : BaseClass
            {
                // Now the display method have been sealed and can;t be overridden
                public override sealed void Display()
                {
                    Console.WriteLine("Sealed method");
                }
            }
    
           //public class ThirdClass : DerivedClass
           //{
    
           //    public override void Display()
           //    {
           //        Console.WriteLine("Here we try again to override display method which is not possible and will give error");
           //    }
           //}
    
            static void Main(string[] args)
            {
    
                DerivedClass ob1 = new DerivedClass();
                ob1.Display();
    
                Console.ReadLine();
            }
        }
    }
    

提交回复
热议问题