简体   繁体   中英

Visual studio debug values changing when looking into them?

So i've been writing some unit tests, and there's one test that fails that shouldn't fail, so I started debugging the test. I looked through the properties and after the debugging was finished, the test passed. weird? So, I ran the test again, and it failed again.

Turns out, the properties(in this case .Selected of an listview-item) actually changed when I looked into it, but it didn't when I don't.....

Here's a video I made to show this weird issue.

https://youtu.be/OsUhh-MlOoU

The documentation for SelectedItems has this to say:

The SelectedItems property will not contain any items if the property is accessed before the ListView handle is created.

Since you're in a test method I would assume you don't actually show the form, nor the listview, on the screen which would require a handle. As such, the listview doesn't get a handle until you force it to.

The act of expanding the listview object in the debug inspector makes the SelectedItems property suddenly contain the element after all which indicates to me that one of the other properties on the ListView type has a side-effect of triggering this creation of a handle.

Here's a small example that demonstrates a similar situation:

void Main()
{
    var x = new Test();
    Console.WriteLine(x.GoodProperty); // place a breakpoint on this line
    Console.WriteLine(x.BadProperty);
    Console.WriteLine(x.GoodProperty);
}

public class Test
{
    public int GoodProperty { get; set; }
    public int BadProperty => GoodProperty++;
}

If you place a breakpoint on the indicated line, then use your mouse to just mouse over the x.GoodProperty expression in the same line, you'll get 0. You can do this over and over again and it still produces 0.

However, every time you mouse over the x.BadProperty expression, x.GoodProperty will also increase by 1.

The exact same thing would happen if you mouse over x and expand it to show all properties. Depending on whether GoodProperty or BadProperty will evaluate first when you expand x , the expanded view may or may not show a changed GoodProperty value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM