c# - 在 C# 中调试时,Visual Studio 如何评估属性?

标签 c# visual-studio properties

过去,调试时我一直被“访问器中的副作用”问题困扰;这意味着我已经在没有触发断点的情况下初始化了缓存(因为它已经在 visual studio 中暂停了)。因此,我一直想知道 Visual Studio 用来“乱序”执行代码的机制,以便在调试器中评估属性。在我看来,这会绕过 CLR 吗?

那么问题来了:从技术角度来看,这是如何做到的?解释它的文章会有所帮助。

最佳答案

看起来像 VS2012(可能还有更早的版本)使用“主线程”或可能是命中断点的线程来执行属性的 getter。

这是我的测试代码:

static class TestSideEffects
{
    public static void Test()
    {
        Console.WriteLine("Main Thread: {0}", Thread.CurrentThread.ManagedThreadId);
        var o = new TestSubject();
        Console.WriteLine("Property Value: {0}", o.IntGetValueNoSe());
    }
}

class TestSubject
{
    private int _prop=0;
    public int TheProperty
    {
        get
        {
            Console.WriteLine("Thread accessing the property: {0}", Thread.CurrentThread.ManagedThreadId);
            return ++_prop;
        }
    } 
    public int IntGetValueNoSe(){return _prop; }
}

我设置了两个断点:在 Test 方法的第 3 行和 getter 本身,每次我将鼠标悬停在 o 实例上时 - 它会执行 getter 而不会触发另一个断点。它使用相同的(在本例中为 main)线程。

这是测试程序的输出:

Main Thread: 8
Thread accessing the property: 8
Thread accessing the property: 8
Thread accessing the property: 8

关于c# - 在 C# 中调试时,Visual Studio 如何评估属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13963820/

相关文章:

visual-studio - 如何在 Visual Studio 中启动单个项目而不进行调试?

c++ - 这个继承自 std::vector 的类声明有问题吗?

java - 在类路径中找不到 Camel 属性文件

用户控件的 ASP.NET 验证消息 "Attribute ... is not a valid attribute of element ..."

c# - Windows 键的 SendKey 是什么

javascript - 在 javascript razor 中比较 2 个 json 并合并为 1 个 json

python - 无法构建使用 Python 的项目

ios - 从不同的类在 webView 上加载 NSURLRequest。

c# - 从 .NET 中的 app.config 或 web.config 读取设置

c# - 具有通用类型约束的工厂模式