问题
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:
- Before a class to avoid inheritance.
- 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