非密封类型的构造函数调用其类中定义的虚方法。
调用虚方法时,直到运行时之前都不会选择执行该方法的实际类型。构造函数调用虚方法时,可能尚未执行调用该方法的实例的构造函数。
要修复与该规则的冲突,请不要从某类型的构造函数中调用该类型的虚方法。
不要禁止显示此规则发出的警告。应重新设计该构造函数,以取消对虚方法的调用。
下面的示例演示与该规则冲突产生的影响。测试应用程序创建 DerivedType 的实例,使其基类 (BadlyConstructedType) 构造函数开始执行。BadlyConstructedType 的构造函数错误地调用虚方法 DoSomething。如输出所示,DerivedType.DoSomething() 将执行,并且是在DerivedType 的构造函数执行前开始执行。
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();
}
}
}
该示例产生下面的输出。
Calling base ctor. Derived DoSomething is called - initialized ? No Calling derived ctor.
参考:https://msdn.microsoft.com/zh-cn/library/ms182331(VS.90).aspx