What are the dangers of making a method virtual?

前端 未结 3 1444
离开以前
离开以前 2021-01-12 11:47

I\'ve been doing some mocking with RhinoMocks and it requires that mocked methods be made virtual. This is fine except we have a custom framework which contains the methods

3条回答
  •  余生分开走
    2021-01-12 11:58

    Actually it can be very problematic if the method is not designed to be overridden and someone overrides it. In particular, never call a virtual method from a constructor. Consider:

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

    The Derived class may not be aware that the virtual method call will result in its InitializeComponent method being called before a single line of its own constructor has run.

提交回复
热议问题