参数是否存储在C#的lambda函数中?

时间:2019-01-21 12:56:11

标签: c# asp.net-core lambda

在ASP.NET Core中,可以使用Func 类型的委托在应用程序中注册中间件中间件。 以下是使用lambda函数注册简单中间件的示例:

public void Configure(IApplicationBuilder app,
                              IHostingEnvironment env,
                              IGreeter greeter,
                              ILogger<Startup> logger)
        {               
            // Outer delegate 
            app.Use((next) =>
            {
                // Inner delegate
                return async (context) =>
                {
                    logger.LogInformation("Request incoming");
                    if (context.Request.Path.StartsWithSegments("/mym"))
                    {
                        await context.Response.WriteAsync("Hit!!");
                        logger.LogInformation("Request handled");
                    }
                    else
                    {
                        await next(context);
                        logger.LogInformation("Request outgoing");
                    }
                };
            });
        }

“使用”方法在框架中实现如下:

public IApplicationBuilder Use(Func<RequestDelegate, RequestDelegate> middleware)
        {
            _components.Add(middleware);
            return this;
        }

至少有一个内部调用的框架函数“ Build”,用于构建依赖项:

public RequestDelegate Build()
        {
            RequestDelegate app = context =>
            {
                // Implicitly execute matched endpoint at the end of the pipeline instead of returning 404
                var endpointRequestDelegate = context.GetEndpoint()?.RequestDelegate;
                if (endpointRequestDelegate != null)
                {
                    return endpointRequestDelegate(context);
                }

                context.Response.StatusCode = 404;
                return Task.CompletedTask;
            };

            foreach (var component in _components.Reverse())
            {
                app = component(app);
            }

            return app;
        }

在foreach部分中,它循环遍历“ Use”函数内的所有外部函数,并将内部委托作为参数传递给它。 当应用程序启动时,外部函数仅被调用一次。在每个HTTP请求中都会调用内部委托。

我的问题是:内部委托人如何知道/记住其“下一个”对象? 在代码中似乎很明显,因为内部委托是在外部委托中调用的,因此它可以访问“下一个”对象。但是如何在内部实现?

0 个答案:

没有答案