使用返回的实例?

Using a returned instance?

我有一个执行 API 请求的 classes 层次结构。在基础class中,我构建了请求对象,在一些子class中,这个方法被覆盖了。

基础class:

      protected virtual HttpRequestMessage BuildRequest(HttpMethod method, Uri uri, HttpContent content = null)
      {
           HttpRequestMessage request = new HttpRequestMessage(method, uri);
           if (null != content)
           {
                request.Content = content;
           }

           return request;
      }

子class:

      protected async override HttpRequestMessage BuildRequest(HttpMethod method, Uri uri, HttpContent content = null)
      {
           HttpRequestMessage request = await base.BuildRequest(method, uri, content);
           request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", AccessTokenHelper.GetAccessToken());

           return request;
      }

然后在其他方法中使用 BuildRequest() 方法的语句:

      using HttpRequestMessage request = BuildRequest(HttpMethod.Post, url, content);

如您所见,我是 using 返回的实例。这是否也会正确处理每个 BuildRequest() 方法中的 HttpRequestMessage 实例?或者这就是class数万次请求后的ic内存泄漏情况?

如果您查看代码,会创建一个实例:

HttpRequestMessage request = new HttpRequestMessage(method, uri);

其他 2 行仅获取对上面创建的实例的引用:

HttpRequestMessage request = await base.BuildRequest(method, uri, content);
using HttpRequestMessage request = BuildRequest(HttpMethod.Post, url, content);

因此,通过使用 using HttpRequestMessage request = BuildRequest(HttpMethod.Post, url, content);,您可以正确处理在基础 BuildRequest 方法中创建的实例。