是什么使得一个虚拟的方法的危险? [英] What are the dangers of making a method virtual?

查看:116
本文介绍了是什么使得一个虚拟的方法的危险?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在做一些嘲讽与RhinoMocks的,它需要嘲笑方法进行虚拟。这很好,除了我们有一个自定义的框架,其中包含我想嘲笑这是目前没有标记为虚拟的方法。

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 that I want to mock which are currently not marked as virtual.

我无法预见作出任何问题这些方法虚拟,但我想知道什么是制作方式的虚拟,我应该去寻找一些潜在的危险?

I can't forsee any problem with making these methods virtual but I was wondering what are some potential dangers of making methods virtual that I should look out for?

推荐答案

其实这可能会遇到很多问题,如果该方法的目的不是要被重写,有人将其覆盖。特别是,从来没有叫从构造一个虚拟的方法。试想一下:

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

派生类可能不知道虚拟方法调用将导致其InitializeComponent方法的单行之前,被称为其自己的构造已运行。

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.

这篇关于是什么使得一个虚拟的方法的危险?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆