FxCop 中有一个rule ConstructorsShouldNotCallBaseClassVirtualMethods
那如果在构造函数中调用Virtual方法可能会产生什么样的不良后果呢?
看如下代码:
public class BaseClass {
public int intCount=0;
public BaseClass() {
Increate();
}
public virtual void Increate(){
intCount++;
}
}
public class SubClass: BaseClass {
public int subCount=0;
public SubClass() {
Increate();
}
public override void Increate() {
subCount++;
}
}
private void button1_Click(object sender, System.EventArgs e)
{
SubClass xx=new SubClass();
MessageBox.Show(xx.intCount.ToString() +"---"+xx.subCount.ToString() );
}
显示的结果是 xx.intCount 是 0;xx.subCount 是 2 ;
原因是 SubClass 的 Increate() 在 SubClass() 被调用之前调用了。
以上代码编译后用FxCop分析,会报如下错误提示:
CriticalWarning, Certainty 95, for "ConstructorsShouldNotCallBaseClassVirtualMethods"
{
Target : ".ctor()" (IntrospectionTargetConstructor)
Location : "file:c:\documents and settings\administrator.hrms-xam\my documents\visual studio projects\windowsapplication1\form1.cs(30)" (String)
Resolution : "'BaseClass..ctor()' contains a call chain that results
in a call to a virtual method defined by the class.
Review the following call stack for unintended consequences:
BaseClass..ctor()BaseClass.Increate(
)"
... ...
.ctor() 为构造函数。
FxCop 代码警察 对于dotNet开发者是非常有用的工具,至少它可以帮助你提高你的代码质量。