16. 不要在封闭类中声明虚成员
翻译概述:
一条比较无聊的规则,并且VB.NET和C#编译器都已经内嵌的禁止代码违反这条规则。
引起的原因:
一个公共的封闭类型中包含虚成员。这条规则不检查delegate类型。因为delegate肯定符合这条规则。
<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />
描述:
一个类型声明虚成员是为了它的继承类型可以重载虚成员的实现。但是,你不能继承一个封闭类型。因此声明封闭类型的虚成员是没有意义的。
VB.NET和C#编译器不允许代码违反这条规则。
修复:
将成员标记成非虚成员或修改类型为可继承的。
例外:
没有例外情况,违反这条规则会增加维护成本,同时,这样做没有任何好处。
例程:
文中的例子使用C++写了一个违反这条规则的例子。
原文引用:
Do not declare virtual members in sealed types
Rule Description
Types declare methods as virtual so that inheriting types can override the implementation of the virtual method. By definition, you cannot inherit from a sealed type, making a virtual method on a sealed type meaningless. The Visual Basic .NET and C# compilers do not allow types to violate this rule. How to Fix Violations
To fix a violation of this rule, make the method non-virtual or make the type inheritable. When to Exclude Messages
Do not exclude a message from this rule. Leaving the type in its current state can cause maintenance issues and does not provide any benefits. Example Code
The following example shows a type that violates this rule. [C++] #using <mscorlib.dll>
using namespace System;
namespace DesignLibrary { __gc __sealed public class SomeType { public: virtual bool VirtualFunction() { return true; } }; } |