2016-08-21 44 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

相关问题