Visual Studio在C#调试时如何评估属性?

9
过去,当我调试时,曾经遇到过“访问器中的副作用”问题,这意味着我的断点没有被触发,缓存已经被初始化了(因为它已经在 Visual Studio 中暂停了)。因此,我一直在想 Visual Studio 用于执行代码“乱序”的机制,以便在调试器中评估属性。对我来说,这似乎会绕过 CLR?
因此,问题是:从技术角度来看,这是如何实现的?解释这个问题的文章将会很有帮助。

我似乎记得一段时间前看到过一篇关于它的文章,但我的谷歌搜索能力太弱了,无法再次找到它。 - Smashery
开始 副作用和表达式 - horgh
1个回答

3

看起来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方法的第三行,另一个在getter函数里面。每当我将鼠标悬停在“o”实例上时,它就会执行getter函数而不触发其他断点。它使用相同的(主要是)线程。

以下是测试程序的输出:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接