Preventing override of individual methods in C#

早过忘川 提交于 2019-12-18 18:33:29

问题


I know that I can use the sealed in order to prevent other classes to inherit a certain class, but is it possible to allow inheritance but prevent overriding of some virtual methods?


回答1:


Only virtual methods can be overridden.
Just leave out virtual, and your method will not be overridable.




回答2:


you can also use sealed modifier to prevent a derived class from further overriding the method.

check this out: Sealed methods




回答3:


Yes. The sealed keyword can also be used on methods, to indicate that a method which is virtual or abstract at higher inheritance levels cannot be further inherited.

If the method was never virtual or abstract to begin with, no worries; it can't be overridden.

Note that sealed only affects method overriding; method hiding cannot be stopped in this way, so a child class can still declare a new method of the same name and signature as your sealed method.




回答4:


You can get the sealed keyword to work on a method in the abstract class by making that abstract class itself derived from something:

abstract class DocumentTemplateBase
{
    public abstract void WriteTitle();
    public abstract void WriteSections();
}

abstract class DocumentTemplate : DocumentTemplateBase
{
    public override sealed void WriteTitle() 
    {
        Console.WriteLine("Project document"); 
    }

    public override sealed void WriteSections() 
    {
        Console.WriteLine("Sections");
    }

    abstract public void WriteContent();
}

Still deriving your concrete class from the original (and now derived) abstract class:

class Document1_FromTemplate : DocumentTemplate
{
    public override void WriteTitle() //error!
    {
        Console.WriteLine("Project1 document");
    }

"cannot override inherited member 'Dynamics.DocumentTemplate.WriteTitle()' because it is sealed"

There is nothing, however to prevent an implementer from newing it:

class Document1_FromTemplate : DocumentTemplate
{
    public new void WriteTitle() //sorry! can't stop it!
    {
        Console.WriteLine("Project1 document");
    }



回答5:


You can use the sealed keyword in two ways:

  1. Before a class to avoid inheritance.
  2. Before a function to avoid overriding.

To allow inheritance don’t put the sealed keyword before the class and to avoid overriding put sealed before the function which you don’t want to be overridden.




回答6:


Yes. you need to use sealed override for the method to achieve it.



来源:https://stackoverflow.com/questions/5274639/preventing-override-of-individual-methods-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!