延迟初始化总是 returns null

Lazy Initialization always returns null

我有以下 class 假设要创建遍历字符串数组以检查代码是否存在。但是,在使用惰性初始化时,.value 总是 returns null。

public class LazyInclusionList
{
    private string docCopyCode;
    private Lazy<LazyInclusionList> _docCopyCodeList = null;
    public LazyInclusionList()
    { }

    public bool GetDocCodes(string docCopyNumber)
    {
        docCopyCode = new string(docCopyNumber.Where(Char.IsLetter).ToArray());
        _docCopyCodeList = new Lazy<LazyInclusionList>();
        bool docCopyCheck = false;
        int last = _docCopyCodeList.Value.GetDocCodesDB.Count();
        int i = 0;

        foreach (string code in _docCopyCodeList.Value.GetDocCodesDB)
        {
            if(docCopyCode == code)
            {
                docCopyCheck = true;
            }
            else if (docCopyCode != code && ++i == last)
            {
                docCopyCheck = false;
            }
        }
        return docCopyCheck;
    }

    private string[] codes;
    public string[] GetDocCodesDB
    {
        set
        {
            codes = value;
        }
        get { return codes; }
    }

}

我有以下测试方法来检查这段代码。

[TestMethod]
public void CheckURLList()
    {
        var list = new LazyInclusionList();
        string[] array = new string [3] { "CB", "DB", "T" };
        list.GetDocCodesDB = array;
        string myTest = "CB10/00/1";
        Assert.IsTrue(list.GetDocCodes(myTest));
    }

第一次使用这种方法,不是很了解

我无法识别您示例中的已知模式,因此我决定用简单的文字来解释这个想法。

The string array will be stored in the DB and do not want to make the trip every time it is needed

基本上就是这样

string[] _codes;
public string[] Codes
{
    get
    {
        if (_codes == null) // check if not initialized yet
        {
            _codes = ... // fill from database
        }
        return codes;
    }
}

一旦您第一次读取 Codes 值,它就会获得,结果是 cachednull 用作 特殊值 到 运行 初始化一次(如果预期 null 作为结果,则可以使用另一个 bool 字段_codes).


Lazy<> 也在做同样的事情(请参阅 this question 了解见解)并且它的用法如下:

readonly Lazy<string[]> _codes = new Lazy<string[]>(() =>
{
    return ... // return here string[] which you fill from database
});
public string[] Codes => _codes.Value; // property used to get value

注意:Lazy<> 的初始化(用于计算其 Value 的 lambda)只会 运行 一次,与上面的缓存示例相同。要进行初始化,您只需访问 Codes 属性 一次,任何进一步的调用都会 return 缓存 结果。