在C#中密封方法 [英] Sealed method in C#

查看:81
本文介绍了在C#中密封方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C#中的新手。我正在阅读有关密封keyword.I已经得到有关密封class.I读了有关密封方法行,我们可以使密封方法also.The线为(通过声明的方法作为密封,可避免这种方法的进一步压倒一切的。
我已经创建了一个演示,但不明白上面的线和密封方法使用的意义。下面是我的代码: -

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 (By declaring method as sealed, we can avoid further overriding of this method.) I have created a demo but didn't understand that the meaning of above line and sealed method use. Below is my code:-

using System;

namespace ConsoleApplication2
{
    class Program:MyClass
    {
        public override sealed void Test()
        {
            Console.WriteLine("My class Program");
        }
        static void Main(string[] args)
        {
            Program obj = new Program();
            obj.Test();
            Console.ReadLine();
        }
    }

    class MyClass
    {
        public virtual void Test()
        {
            Console.WriteLine("My class Test");
        }
    }


}

请告诉我,为什么我们使用密封的方法,什么是密封方法的优点。

Please tell me why we use Sealed methods and what are the advantages of Sealed methods.

推荐答案

那么,你与测试只有两个级别继承,而你没有得到到你,进一步压倒一切的方法点。如果你把它三,你可以看到密封所做的:

Well, you are testing with only two levels of inheritance, and you are not getting to the point that you're "further overriding" a method. If you make it three, you can see what sealed does:

class Base {
   public virtual void Test() { ... }
}
class Subclass1 : Base {
   public sealed override void Test() { ... }
}
class Subclass2 : Subclass1 {
   public override void Test() { ... } // FAILS!
   // If `Subclass1.Test` was not sealed, it would've compiled correctly.
}

这篇关于在C#中密封方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆