运行 在 C# 中多次使用不同参数的相同方法

Running the same method multiple times with different parameters in c#

我打电话给 API 是为了获取一个联系人列表(他们可能有 100 或 1000 个)并且列表一次只列出 100 个并且它给我这个分页选项在末尾有一个对象名为 'nextpage' 的列表和 URL 到下一个 100 等等..

所以在我的 c# 代码中,我得到前 100 个并循环遍历它们(做某事)并查找 'nextpage' 对象并获取 URL 并重新调用 API 等.. 看起来这个下一页链继续取决于我们有多少联系人。

你能告诉我是否有办法让我循环遍历相同的代码并且仍然能够使用来自 'nextpage' 对象的新 URL 和 运行 逻辑我每得到 100 个?

伪代码,因为我们没有具体的例子可以使用,但是...

大多数带分页的 API 都有项目总数。您可以设置每次迭代的最大项目数并像那样跟踪它,或者检查空值 next_object,具体取决于 API 处理它的方式。

    List<ApiObject> GetObjects() {

        const int ITERATION_COUNT = 100;
        int objectsCount = GetAPICount();

        var ApiObjects = new List<ApiObject>();

        for (int i = 0; i < objectsCount; i+= ITERATION_COUNT) {

            // get the next 100
            var apiObjects = callToAPI(i, ITERATION_COUNT); // pass the current offset, request the max per call
            ApiObjects.AddRange(apiObjects);

        }   // this loop will stop after you've reached objectsCount, so you should have all

        return ApiObjects;
    }

    // alternatively:

    List<ApiObject> GetObjects() {

        var nextObject = null;
        var ApiObjects = new List<ApiObject>();

        // get the first batch
        var apiObjects = callToAPI(null);
        ApiObjects.AddRange(apiObjects);
        nextObject = callResponse.nextObject;

        // and continue to loop until there's none left
        while (nextObject != null) {            
            var apiObjects = callToAPI(null);
            ApiObjects.AddRange(apiObjects);
            nextObject = callResponse.nextObject;   
        }

        return apiObjects;  
    }

根据两种常用的 Web 服务方法,这就是基本思想(省略了很多细节,因为这不是工作代码,只是为了演示一般方法)。