[英]Lazy property getting value before first get
最初有代码:
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 */ }
}
代码说:“让我们发现错误!” 并且有错误。
现在认真。
我有一个实例B
,当我得到SomeValue
,我得到相同SomeValue
的A
,而MoreValue。
当我在SomeValue
的Get方法上设置断点时,出现了更奇怪的部分:
事实证明, _someValue
在调用Get方法之前获取其值。
这里有些错误。
更新:
感谢您的评论! 缩短代码,并在B方法中添加了忘记的返回类型。
原来我犯了一个愚蠢的错误。
(我将删除该问题,但我认为其他人可以从我的工作人员那里学习。)
我看了SomeValue
。
结果? 我开始调试的那一刻被称为Get SomeValue
。
(这有点奇怪,因为我在Get
方法上有一个未激活的断点。由于某种原因, watch
es不会触发断点。)
*(至于错误的值,与继承无关-
GetMoreValue
只是碰巧返回了一个空字符串。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.