CA2214: Nevolejte přepisovatelné metody v konstruktorech
TypeName |
DoNotCallOverridableMethodsInConstructors |
CheckId |
CA2214 |
Kategorie |
Microsoft.Usage |
Narušující změna |
Nenarušující |
Příčina
Konstruktor nezapečetěného typu volá virtuální metodu definovanou v jeho třídě.
Popis pravidla
Při volání virtuální metody není skutečný typ, který metodu spouští, zvolen až do doby spuštění.Volá-li konstruktor virtuální metodu, může se stát, že konstruktor instance volající metodu nebyl spuštěn.
Jak vyřešit porušení
Chcete-li opravit porušení tohoto pravidla, nevolejte virtuální metody typu v jeho konstruktorech.
Kdy potlačit upozornění
Nepotlačujte upozornění na toto pravidlo.Konstruktor by měl být znovu navržen tak, aby v něm nebylo volání virtuální metody.
Příklad
Následující příklad ukazuje důsledky porušení tohoto pravidla.Testovací aplikace vytvoří instanci třídy DerivedType, což způsobuje spuštění konstruktoru její základní třídy (BadlyConstructedType).Konstruktor třídy BadlyConstructedType nesprávně volá virtuální metodu DoSomething.Jak ukazuje výstup, je metoda DerivedType.DoSomething() spuštěna před spuštěním konstruktoru třídy DerivedType.
Imports System
Namespace UsageLibrary
Public Class BadlyConstructedType
Protected initialized As String = "No"
Public Sub New()
Console.WriteLine("Calling base ctor.")
' Violates rule: DoNotCallOverridableMethodsInConstructors.
DoSomething()
End Sub 'New
' This will be overridden in the derived type.
Public Overridable Sub DoSomething()
Console.WriteLine("Base DoSomething")
End Sub 'DoSomething
End Class 'BadlyConstructedType
Public Class DerivedType
Inherits BadlyConstructedType
Public Sub New()
Console.WriteLine("Calling derived ctor.")
initialized = "Yes"
End Sub 'New
Public Overrides Sub DoSomething()
Console.WriteLine("Derived DoSomething is called - initialized ? {0}", initialized)
End Sub 'DoSomething
End Class 'DerivedType
Public Class TestBadlyConstructedType
Public Shared Sub Main()
Dim derivedInstance As New DerivedType()
End Sub 'Main
End Class
End Namespace
using System;
namespace UsageLibrary
{
public class BadlyConstructedType
{
protected string initialized = "No";
public BadlyConstructedType()
{
Console.WriteLine("Calling base ctor.");
// Violates rule: DoNotCallOverridableMethodsInConstructors.
DoSomething();
}
// This will be overridden in the derived type.
public virtual void DoSomething()
{
Console.WriteLine ("Base DoSomething");
}
}
public class DerivedType : BadlyConstructedType
{
public DerivedType ()
{
Console.WriteLine("Calling derived ctor.");
initialized = "Yes";
}
public override void DoSomething()
{
Console.WriteLine("Derived DoSomething is called - initialized ? {0}", initialized);
}
}
public class TestBadlyConstructedType
{
public static void Main()
{
DerivedType derivedInstance = new DerivedType();
}
}
}
Tento příklad vytvoří následující výstup.