抽象类的密封性能
请考虑下面的设计:
public interface IBook
{
string Author { get; set; }
string Title { get; set; }
}
abstract class BaseBook : IBook
{
private string _title;
public virtual string Author
{
get
{
Console.WriteLine("Base book GET!");
return _title;
}
set
{
Console.WriteLine("Base book SET!");
_title = value;
}
}
public string Title { get; set; }
}
class Book : BaseBook
{
}
class SuperBook : Book
{
public override string Author
{
get
{
Console.WriteLine("SuperBook GET!");
return base.Author;
}
set
{
Console.WriteLine("SuperBook SET!");
base.Author = value;
}
}
public string Title { get; set; }
}
有没有什么办法让标题
的 BaseBook
基类属性的密封,以防止在派生类(如图书和 SuperBook
班)?
Is there any way make the Title
property of the BaseBook
base class sealed to prevent the property from being overridden in derived classes (such as the Book
and the SuperBook
classes)?
如果您编译程序时,您会收到以下警告:
If you compile your program, you will receive the following warning:
prog.cs(63,19):警告CS0108 : SuperBook.Title隐藏继承
BaseBook.Title。使用新的
会员
如果关键字藏身之意。
prog.cs(63,19): warning CS0108:
SuperBook.Title' hides inherited member
BaseBook.Title'. Use the new keyword if hiding was intended
这意味着你的 SuperBook.Title
躲藏起来从BaseBook标题。隐藏是压倒一切的不同,因为成员不虚。有什么隐藏发生是这样的:如果的编译的是治疗你的对象作为SuperBook类的一个实例,它会调用 SuperBook.Title
方法。但是,如果编译器会将您的实例作为BaseBook类,呼叫将被制成 BaseBook.Title
。
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
.
例如:
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.
最后,如果你想要的属性是虚拟的让每一个电话得到解决,以 SuperBook.Title
,但不希望用户覆盖它更多的派生类,所有你需要做的标记属性封控
。
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
.