<分区>
Possible Duplicate:
Virtual member call in a constructor
首先,为什么在C#中的ctor内部调用虚函数不是错误?
其次,如果允许,为什么 Resharper 仍然对此发出警告?
<分区>
Possible Duplicate:
Virtual member call in a constructor
首先,为什么在C#中的ctor内部调用虚函数不是错误?
其次,如果允许,为什么 Resharper 仍然对此发出警告?
最佳答案
已回答:
Virtual member call in a constructor
简而言之,它与构造函数的调用顺序有关,这与调用虚方法的顺序不同:构造函数从不太具体到最具体,而虚方法从最具体的到不太具体的调用。
这意味着你可能会落入这个陷阱:
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");
}
}
关于c# - Resharper 警告在构造函数中使用虚函数,但与 C++ 不同,这不是错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3282644/
相关文章:
javascript - Visual Studio - 如何将 javascript 字符串从双引号重构为单引号
c# - SqlFunctions.StringConvert() 不工作 ef 核心
c# - 在不知道事件的具体类型的情况下恢复持久的 Window Workflow 4 事件
.net - 所有测试均通过,但 TFS 将构建标记为部分成功
c# - 为什么 ReSharper 想要对所有内容使用 'var'?
c# - 在 VBA 中早期绑定(bind) C# COM 库
c# - 什么是更好的设计/实践 : Nullable property or 1 value property and 1 bool "has" property?
c# - 当 Resharper 显示 'Failed to modify Documents' 时,我需要一个解决方法。有谁知道它为什么这样做以及如何解决它?