c# - Propery getter automatically called when debugging for passive property

拜拜、爱过 提交于 2019-12-12 21:59:39

问题


I recently was working with some code with a property that exposed a field that was updated/created passively, that is only when getting it and some flag indicated that the field needed updating. This is the code:

static void Main(string[] args)
{
        var someClass  = new SomeClass();
        Console.WriteLine(someClass.ClassString);
        Console.ReadKey();
}

class SomeClass
{
    private bool _dirtyFlag;

    private String _classString;

    public String ClassString
    {
        get
        {
            Console.WriteLine("dirty flag value in getter: " + _dirtyFlag);
            Console.WriteLine("_classString value in getter: " + _classString);
            if (_dirtyFlag)
            {
                _classString = "new value";
                _dirtyFlag = false;
            }
            return _classString;
        }
    }

    public SomeClass()
    {

        SetDirtyFlag();

        Console.WriteLine("dirty flag value in constructor: " + _dirtyFlag);

        Console.WriteLine("_classString value in constructor: " + _classString);

    }


    public void SetDirtyFlag()

    {
        _dirtyFlag = true;
    }
}

When debugging the code I found some weird behavior: the flag value was set automatically from true to false and the _classString updated even when ClassString was not called (somehow the getter was called from somewhere else than the code). Additionally, setting a breakpoint in the ClassString getter would not show when the getter was called for the first time (which was not a call from my code). I would get outputs like:

dirty flag value in getter: True
_classString value in getter:
dirty flag value in constructor: False
_classString value in constructor: new value
dirty flag value in getter: False
_classString value in getter: new value
new value

What is causing this weird behavior? Who is calling the getter before my code does?


回答1:


The debugger is calling your getter code before your code does.

When debugging your code and only if you are inspecting the value of ClassString (when the variable is visible in the Locals window of Visual Studio), then Visual Studio will try to get the value of the variables to show them in the debugging window. Then in this case the getter is called and your variables are updated according to your code.

It is also worth noting that this getter call from the Debugger does not stop if there is a breakpoint, since breakpoints only apply to the main execution thread. In other words, the debugger calls of code ignore the breakpoints.



来源:https://stackoverflow.com/questions/54772870/c-sharp-propery-getter-automatically-called-when-debugging-for-passive-propert

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!