【问题标题】:Stop Visual Studio 2019 from constantly evaluating ToString()阻止 Visual Studio 2019 不断评估 ToString()
【发布时间】:2019-04-16 17:30:06
【问题描述】:

重现我的问题:

  1. 将以下代码粘贴到 Visual Studio 2019 中的新 C# .NET Framework 控制台应用程序中。
  2. _Bar = null行上放一个断点
  3. 开始调试
  4. 在断点处,将鼠标悬停在_Bar 上以查看其值
  5. 跳过
  6. 跳过
  7. 抛出异常

看起来 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


【解决方案1】:

问题的解决方法是在常规调试选项中禁用属性评估

编辑:如果您没有带有属性的监视窗口,则该问题的另一种解决方案。

【讨论】:

    猜你喜欢
    • 2015-10-12
    • 1970-01-01
    • 2020-03-27
    • 1970-01-01
    • 2020-03-04
    • 2019-05-16
    • 1970-01-01
    • 2013-05-31
    • 1970-01-01
    相关资源
    最近更新 更多