代码改变世界

[FxCop.设计规则]16. 不要在封闭类中声明虚成员

2005-08-08 20:04  Colin Han  阅读(1007)  评论(0编辑  收藏  举报

16.     不要在封闭类中声明虚成员

翻译概述:

一条比较无聊的规则,并且VB.NETC#编译器都已经内嵌的禁止代码违反这条规则。

引起的原因:

一个公共的封闭类型中包含虚成员。这条规则不检查delegate类型。因为delegate肯定符合这条规则。

 

描述:

一个类型声明虚成员是为了它的继承类型可以重载虚成员的实现。但是,你不能继承一个封闭类型。因此声明封闭类型的虚成员是没有意义的。

 

VB.NETC#编译器不允许代码违反这条规则。

修复:

将成员标记成非虚成员或修改类型为可继承的。

例外:

没有例外情况,违反这条规则会增加维护成本,同时,这样做没有任何好处。

 

例程:

文中的例子使用C++写了一个违反这条规则的例子。

原文引用:

Do not declare virtual members in sealed types

TypeName:

DoNotDeclareVirtualMembersInSealedTypes

CheckId:

CA1048

Category:

Microsoft.Design

Message Level:

Error

Certainty:

95%

Breaking Change:

Breaking


Cause: A public type is sealed and declares a method that is both virtual (Overridable in Visual Basic) and not final. This rule does not report violations for delegate types, which must follow this pattern.

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; }

    };

}