C# 如果属性已设置,如何防止调用该函数?

C# 如果属性已设置,如何防止调用该函数?,c#,properties,C#,Properties,我有一个函数,可以在一个类中设置两个列表,以便从第三方获取。 我把它放在一个函数中,因为访问第三方需要时间,我只想为这个页面做一次。 这是我的班级: public class MyClass { public IEnumerable<dynamic> ListOne { get; set; } public IEnumerable<dynamic> ListTwo { get; set; } } 因此,现在在我的web API中有两个函数——一个返回每个

我有一个函数,可以在一个类中设置两个列表,以便从第三方获取。
我把它放在一个函数中,因为访问第三方需要时间,我只想为这个页面做一次。 这是我的班级:

public class MyClass
{
    public IEnumerable<dynamic> ListOne { get; set; }
    public IEnumerable<dynamic> ListTwo { get; set; }
}
因此,现在在我的web API中有两个函数——一个返回每个列表

    [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);
        }
[路由(“列表通”)]
公共IHttpActionResult GetListOne()
{
IEnumerable ListOne=GetLists().ListOne;
返回Json(ListOne);
}
[路线(“列表二”)]
公共IHttpActionResult GetListTwo()
{
IEnumerable ListTwo=GetLists().ListTwo;
返回Json(ListTwo);
}
我的问题是每次调用webApi getListone或getListTwo时,该函数都会再次运行并调用第三方。我怎样才能防止这种情况


谢谢大家!

将数据检索逻辑放入属性并延迟加载数据,即在第一次调用属性时加载数据

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;
    }
}
private IEnumerable\u listOne;
公共IEnumerable列表{
得到{
如果(_listOne==null){
//在这里检索数据。当然,您可以调用
//您已经在其他地方实现了更复杂的逻辑。
_listOne=ThirdParty.listOne??可枚举的.Empty();
}
返回_listOne;
}
}
??Enumerable.Empty()
确保永远不会返回null。相反,将返回一个空枚举

参见:和


另外,请查看。

谢谢您的回复。我有两个问题a)我认为我不应该在属性本身中放置大量代码?(连接到第三方需要相当多的代码)b)如果我的ThirdParty.listOne恰好返回null,它将再次执行,否?您可以将主数据检索逻辑放在其他地方,然后从属性调用此逻辑。我认为属性不应该调用数据库调用之类的东西,基于以下帖子:@shw:See and。另请参见Eric Lippert的博客。
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;
    }
}