调试期间鼠标悬停(DataTip)后自动实例化的属性

ste*_*ano 1 c# visual-studio-debugging

大家晚上好。我发生了一些非常奇怪的事情。经过多次测试,我发现,在调试模式(Visual Studio 2017)下,通过鼠标悬停在属性上出现DataTip后,它被独立实例化并设置为空。它是 Visual Studio 中的错误还是发生这种情况的原因?

    private List<int> myVar;
    public List<int> MyProperty
    {
        get
        {
            if (myVar == null)
            {
                myVar = new List<int>();
                return myVar;
            }
            else
                return myVar;
        }
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        List<int> list = MyProperty;
    }
Run Code Online (Sandbox Code Playgroud)

鼠标悬停在 myVar 上

如您所见,如果您将鼠标放在 myVar 上,您将正确获得 null,但是如果您将其放在 MyProperty 上,它会自动实例化,并且 myVar 也会立即实例化。

鼠标悬停在 MyProperty 上这种行为在调试过程中给我带来了很多问题,我花了很长时间才弄清楚发生了什么。这是正常行为还是错误?请注意,我没有提供 set 访问器。

Ale*_*lex 5

这是正常的行为。

MyProperty每次尝试获取其值都会调用 getter 。调试时悬停也很重要。如果您将光标放在myVar 避免 MyProperty它上面myVar|null,但是一旦您将它放在上面MyProperty,整个 getter 就会调用并且您会看到MyProperty|Count = 0。从那时起myVar就是myVar|Count = 0太(因为它是在吸气改变)。如果你放置一个计数器来知道 getter 调用了多少次,你就会看到它是如何变化的。

在此处输入图片说明

顺便一提,

private List<int> myVar;
public List<int> MyProperty => myVar ?? (myVar = new List<int>());
Run Code Online (Sandbox Code Playgroud)

做同样的事情,但看起来更整洁;)