解决方法
实际上,如果该方法不是被设计为被覆盖并且有人覆盖它,那么它可能是非常有问题的.特别是,永远不要从构造函数中调用虚方法.考虑:
- class Base {
- public Base() {
- InitializeComponent();
- }
- protected virtual void InitializeComponent() {
- ...
- }
- }
- class Derived : Base {
- private Button button1;
- public Derived() : base() {
- button1 = new Button();
- }
- protected override void InitializeComponent() {
- button1.Text = "I'm gonna throw a null reference exception"
- }
- }
Derived类可能不知道虚方法调用将导致在其自己的构造函数的单行运行之前调用其InitializeComponent方法.