Preventing a C# subclass from overwriting a method

后端 未结 4 1343
清歌不尽
清歌不尽 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.

提交回复
热议问题