关于C.I:RESHARPER警告在构造函数中使用虚函数,但与C++不同,它不是一个错误。

Resharper warns about using a virtual function in a constructor, but unlike C++ it is not an error

本问题已经有最佳答案,请猛点这里访问。

Possible Duplicate:
Virtual member call in a constructor

首先,为什么在c中调用一个ctor内部的虚函数不是一个错误?其次,如果允许的话,为什么Resharper还要警告呢?


已回答:

构造函数中的虚拟成员调用

简言之,它与调用构造函数的顺序有关,这与调用虚拟方法的顺序不同:构造函数是从较不特定的调用到最特定的调用,而虚拟方法是从最特定的调用到较不特定的调用。

这意味着你可以掉进这个陷阱:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class Base {
  protected virtual void DoSomething() {
    // do nothing
  }

  public Base() {
    DoSomething();
  }
}

public class Another : Base {
  private List<string> list;

  public Another() {
    list = new List<string>();
  }

  protected override void DoSomething() {
    // this code will raise NullReferenceException,
    // since this class' constructor was not run yet,
    // still, this method was run, since it was called
    // from the Base constructor
    list.Add("something");
  }
}

至于为什么这不是一个错误,请查看维基百科:

For some languages, notably C++, the
virtual dispatching mechanism has
different semantics during
construction and destruction of an
object. While it is recommended that
virtual function calls in constructors
should be avoided for C++ [3], in some
other languages, for example Java and
C#, the derived implementation can be
called during construction and design
patterns such as the Abstract Factory
Pattern actively promote this usage in
languages supporting the ability.

至于问题的第二部分,Resharper会对此发出警告,因为如果你不知道自己在做什么,它可能会产生一些意想不到的结果。有关详细信息,请查看:

构造函数中的虚拟成员调用