Preventing a C# subclass from overwriting a method

后端 未结 4 1337
清歌不尽
清歌不尽 2021-01-18 09:05

Say I have an abstract parent class called \"Parent\" that implements a method called \"DisplayTitle\". I want this method to be the same for each subclass that inherits \"

相关标签:
4条回答
  • 2021-01-18 09:34

    A derived class cannot override your method, you didn't declare it virtual. Note how that's very different in C# compared to Java, all methods are virtual in Java. In C# you must explicitly use the keyword.

    A derived class can hide your method by using the same name again. This is probably the compile warning you are talking about. Using the new keyword suppresses the warning. This method does not in any way override your original method, your base class code always calls the original method, not the one in the derived class.

    0 讨论(0)
  • 2021-01-18 09:39

    How can I accomplish this in C#. I believe in Java, I'd just mark the method as "final", but I can't seem to find an alternative in C#.

    The rough equivalent is sealed in C#, but you normally only need it for virtual methods - and your DisplayTitle method isn't virtual.

    It's important to note that ChildSubclass isn't overriding DisplayTitle - it's hiding it. Any code which only uses references to Parent won't end up calling that implementation.

    Note that with the code as-is, you should get a compile-time warning advising you to add the new modifier to the method in ChildSubclass:

    public new void DisplayTitle() { ... }
    

    You can't stop derived classes from hiding existing methods, other than by sealing the class itself to prevent the creation of a derived class entirely... but callers which don't use the derived type directly won't care.

    What's your real concern here? Accidental misuse, or deliberate problems?

    EDIT: Note that the warning for your sample code would be something like:

    Test.cs(12,19): warning CS0108:
            'ConsoleApplication1.ChildSubclass.DisplayTitle()' hides inherited
            member 'ConsoleApplication1.Parent.DisplayTitle()'. Use the new keyword
            if hiding was intended.
    

    I suggest you turn warnings into errors, and then it's harder to ignore them :)

    0 讨论(0)
  • 2021-01-18 09:46

    Use the sealed modifier to prevent subclasses from overriding your classes, properties, or methods. What isn't working when you use sealed?

    http://msdn.microsoft.com/en-us/library/88c54tsw.aspx

    0 讨论(0)
  • 2021-01-18 09:50

    I'm fairly certain that what you want is not possible in C# using method modifier keywords.

    Sealed only applies when overriding a virtual method in an ancestor class, which then prevent further overriding.

    0 讨论(0)
提交回复
热议问题