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


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

        };

    }

     

  • 相关阅读:
    设计模式与23种设计模式的简单介绍
    一文读懂C++ Vector在算法竞赛中的常见用法
    一文读懂C++ String类在算法竞赛中的常见用法
    GO语言的单元测试与性能测试
    变量提升和函数提升及二者优先级
    闭包
    读《你不知道的JavaScript 中》-异步【3】Promise
    js数组方法-改变原数组和不改变原数组
    读《你不知道的JavaScript 中》-异步【2】回调
    组合类算法问题
  • 原文地址:https://www.cnblogs.com/Cajon/p/210249.html
Copyright © 2020-2023  润新知