Sealed property of abstract class

筅森魡賤 提交于 2019-12-06 02:42:54

If you compile your program, you will receive the following warning:

prog.cs(63,19): warning CS0108: SuperBook.Title' hides inherited memberBaseBook.Title'. Use the new keyword if hiding was intended

This means that your SuperBook.Title is hiding the Title from BaseBook. Hiding is different from overriding, because the member is not virtual. What happens with hiding is this: if the compiler is treating your object as an instance of the SuperBook class, it will call the SuperBook.Title method. If, however, the compiler treats your instance as a BaseBook class, the call will be made to BaseBook.Title.

For instance:

SuperBook b1 = new SuperBook();
Console.Writeline(b1.Title); // will result in a call to SuperBook.Title
BaseBook b2 = b1;
Console.Writeline(b1.Title); // will result in a call to BaseBook.Title

If you make the property virtual, then the result is that the most derived implementation will always be called, because the compiler uses an virtual table to find which method to call.

Finally, if you want the property to be virtual so that every call gets resolved to SuperBook.Title, but don't want the user to override it on more derived classes, all you have to do mark the property sealed override.

If it's not virtual, then it cannot be overriden, it can only be hid (using thenewkeyword). Unlike Java, C# methods (and and by extension properties) are not implicitly virtual, but rather explicitly.

You won't be able to override the Title property unless it is marked virtual anyway. What you cannot prevent it from is being hidden by somebody using the new operator.

You already cannot override BaseBook.Title. SuperBook.Title actually hides BaseBook.Title rather than overrides it. It should really have the new keyword on it if hiding was intended; in fact you'll get a compiler warning to that effect.

Use "sealed" keyword on your Title property.

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