2016-08-21 41 views
1

我有一個函數,可以在一個類中設置2個列表以從第三方提取。
我把它放在一個函數中,因爲去第三方需要時間,我只想爲這個頁面做一次。 這是我的課:如果屬性已經設置,我該如何防止函數被調用?

public class MyClass 
{ 
    public IEnumerable<dynamic> ListOne { get; set; } 
    public IEnumerable<dynamic> ListTwo { get; set; } 
} 

這是我的職責,設置&返回列表

public MyClass GetLists() 
    { 
      //Here I have the code that connects to the third party etc 
      //Here set the items.. from the third party 
      MyClass _MyClass = new MyClass(); 
      _MyClass.ListOne = ThirdParty.ListOne; 
      _MyClass.ListTwo = ThirdParty.ListTwo; 
      return (_MyClass); 
     }; 
    } 

所以,現在在我的web API我有2個功能 - 它返回每個列表。

[Route("ListOne")] 
    public IHttpActionResult GetListOne() 
     { 
     IEnumerable<dynamic> ListOne = GetLists().ListOne; 
     return Json(ListOne); 
     } 

    [Route("ListTwo")] 
    public IHttpActionResult GetListTwo() 
     { 
     IEnumerable<dynamic> ListTwo = GetLists().ListTwo; 
     return Json(ListTwo); 
     } 

我的問題是,每一個我稱之爲的WebAPI getListone或getListTwo時間,該功能將再次運行,並調用第三方。我怎樣才能防止這一點?

謝謝!

回答

1

將數據檢索邏輯放入屬性並延遲加載數據,即在第一次調用屬性時加載數據。

private IEnumerable<dynamic> _listOne; 
public IEnumerable<dynamic> ListOne { 
    get { 
     if (_listOne == null) { 
      // Retrieve the data here. Of course you can just call a method of a 
      // more complex logic that you have implemented somewhere else here. 
      _listOne = ThirdParty.ListOne ?? Enumerable.Empty<dynamic>(); 
     } 
     return _listOne; 
    } 
} 

?? Enumerable.Empty<T>()確保不會返回null。相反,將返回一個空的枚舉。

見:?? Operator (C# Reference)
              Enumerable.Empty Method()

也有看Lazy<T> Class

+0

謝謝你的回覆。我有兩個問題a)我認爲我不應該在財產本身中投入很多代碼? (連接到第三方時有相當多的代碼)b)如果我的ThirdParty.listOne恰好返回null,它會再次執行,不是? – shw

+0

你可以把主要的數據檢索邏輯放在別的地方,只是從屬性中調用這個邏輯。 –

+0

我會這樣做的。謝謝 – shw

相關問題