문제

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, watches don't trigger breakpoints.)

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top