Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 惰性属性在首次获取之前获取值_C#_Inheritance_Overriding_Abstract Class_Lazy Initialization - Fatal编程技术网

C# 惰性属性在首次获取之前获取值

C# 惰性属性在首次获取之前获取值,c#,inheritance,overriding,abstract-class,lazy-initialization,C#,Inheritance,Overriding,Abstract Class,Lazy Initialization,起初,有一个代码: public abstract class A { private string _someValue; public string SomeValue { get { if (_someValue == null) _someValue = GetValue(); return _someValue; } }

起初,有一个代码:

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 */ }
}
代码说,让有bug吧!还有虫子

现在说真的

我有一个B的实例,当我得到SomeValue时,我得到了与A相同的SomeValue,没有更多的值

更奇怪的是,我在SomeValue的Get方法上设置了一个断点: 结果是_someValue在调用Get方法之前就得到了它的值

这里有点不对劲

更新:
谢谢你的评论!缩短了代码,并在B方法中添加了遗忘的返回类型。

结果证明我犯了一个愚蠢的错误。 我想删除这个问题,但我想其他人可以从我的博客中学习

我有一只手表在某个值钱的地方

结果如何?Get-SomeValue在我开始调试时被调用。 这有点奇怪,因为我在Get方法上有一个未激活的断点。出于某种原因,手表不会触发断点

*至于错误的值,这与继承无关-
GetMoreValue只是碰巧返回了一个空字符串。

请发布a。让您的代码编译B。GetValue需要一个返回类型;A.GetValue和B.GetMoreValue需要初始化返回,然后调试您的示例,您将看到它按预期工作。B.SomeValue包含这两个值。我敢打赌,您正在查找的bug在遗漏的代码中的某个地方,因此您已经采取了非常重要的步骤来定位它。我测试了它,它运行良好,调用了B的GetMoreValue。我遗漏了什么吗?您是否正在调试,是否已将调试器配置为自动检索属性值?如果调试器自动读取SomeValue,_SomeValue将被设置。@JacobSpire这是VS、工具、选项、调试、常规中的启用属性求值和其他隐式函数调用设置。