2017-03-16 132 views
0

我有以下類,假設通過字符串數組來創建迭代來檢查代碼是否存在。但是,使用延遲初始化時,.value總是返回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)); 
    } 

這是我第一次使用這種方法,並沒有完全理解它。

+0

我沒有看到構造函數或字段/屬性初始值設定項正在執行任何操作,那麼您如何期望執行'GetDocCodes()'方法(不是說您的測試,而是關於將使用該類型的東西)?您誤解了['Lasy <>'](https://msdn.microsoft.com/en-us/library/dd997286(v = vs.110).aspx)模式。也許如果你用文字解釋你想達到什麼目標,那麼答案會更容易。 – Sinatr

+0

字符串數組將存儲在數據庫中,並且不想在每次需要時執行該行程(如果完全相同)(GetDocCodesDB)。我希望GetDocCodes能夠完成這項工作(返回true/false),並且使用惰性模式來管理對GetDocCodesDB的調用。我希望明確.. –

回答

0

我無法識別您的示例中已知的模式,我決定用簡單的詞語來解釋這個想法。

字符串數組將被存儲在數據庫中,不希望每次需要

時間這基本上就是這個

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

只要你讀Codes成行其首次獲得的結果是緩存null用作特殊值以運行初始化一次(如果null預期爲_codes的結果,則可以使用另一個bool字段)。


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)將只運行一次,與上面的緩存示例相同。對於初始化發生,您只需訪問Codes屬性一次,任何進一步的調用將返回緩存的結果。

+0

我仍然不知何故面臨同樣的問題,即使我給了字符串[]代碼的值,'_codes'爲null –

+0

然後'null'是你從數據庫讀取的結果(代碼是什麼返回'string []'返回'null')。要麼設置一個斷點來查看它,要麼進行一些調試輸出。我的擔憂(和答案)主要是你如何實現'Lazy <>'。 – Sinatr