【发布时间】:2019-04-16 17:30:06
【问题描述】:
重现我的问题:
- 将以下代码粘贴到 Visual Studio 2019 中的新 C# .NET Framework 控制台应用程序中。
- 在
_Bar = null行上放一个断点 - 开始调试
- 在断点处,将鼠标悬停在
_Bar上以查看其值 - 跳过
- 跳过
- 抛出异常
看起来 Visual Studio 一直在评估 ToString() 方法,导致 _Bar 始终具有值 FooBar,尽管它设置为 null。有没有办法阻止它?该问题在 Visual Studio 2013 中不可重现。我使用的是 Visual Studio Community 2019 版本 16.0.1。
using System;
namespace FooBar {
class Program {
static void Main(string[] args) {
new Foo();
}
class Foo {
string _Bar;
public string Bar {
get {
if (_Bar == null) {
_Bar = "FooBar";
}
return _Bar;
}
set {
_Bar = value;
}
}
public Foo() {
_Bar = null;
if (_Bar != null) {
throw new Exception("_Bar is not null.");
}
}
public override string ToString() {
return Bar;
}
}
}
}
【问题讨论】:
-
每次获得 _Bar 时,如果它为空,则将其设置为 foobar。
-
@Scriven Tha 对于
Bar是正确的,但不是_Bar -
“看起来 Visual Studio 正在不断地评估 ToString() 方法” - 你确定它不只是评估监视窗口中的 Bar 属性吗?从根本上说,这是在属性获取器中包含副作用的问题......
-
VS 认为属性 getter 没有副作用,因此会评估它们。它不会对方法这样做。
-
@JonSkeet 你说得对,我没有在以前版本的 Visual Studio 中自动显示监视窗口。从 VS2019 的监视列表中删除对象就可以了
标签: c# visual-studio visual-studio-2019