简体   繁体   中英

Lazy property getting value before first get

In the beginning, there was code:

public abstract class A
{
    private string _someValue;

    public string SomeValue
    {
        get
        {
            if (_someValue == null)
                _someValue = GetValue();
            return _someValue;
        }
    }

    protected virtual string GetValue() { /* logic */ }
}

public class B : A
{
    protected override string GetValue()
    {
        return base.GetValue() + GetMoreValue();
    }

    private string GetMoreValue() { /* logic */ }
}

And the code said, "Let there be bugs!" and there were bugs.


Seriously now.

I have an instance of B , and when I get SomeValue , I get the same SomeValue of A , without the MoreValue.

The even weirder part came when I put a breakpoint on SomeValue 's Get method:
It turns out that _someValue gets its value before the Get method is ever called .

Something is very wrong here.


UPDATE:
Thanks for the comments! Shortened code, and added forgotten return type in B method.

It turns out I was making a stupid mistake.
(I would delete the question, but I figured others can learn from my blooper.)

I had a watch on SomeValue .

The result? Get SomeValue was called the moment I started debugging.
(Which is a little weird, because I had a breakpoint on the Get method which didn't activate. For some reason, watch es don't trigger breakpoints.)

*(As for the wrong value, that had nothing to do with inheritance -
GetMoreValue simply happened to return an empty string.)

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