【问题标题】:Null Conditional Operator, not behaving as expected on some machines空条件运算符,在某些机器上的行为不符合预期
【发布时间】:2016-09-10 03:46:11
【问题描述】:

我在 WebApi 2 项目的 DelegatingHandler 中有以下代码。

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var content = await request.Content?.ReadAsStringAsync();
        _log.Information("Received {request} with content body: {content}.", request, content);

        // Run the rest of the request pipeline.
        var result = await base.SendAsync(request, cancellationToken);

        var responseContent = await result.Content?.ReadAsStringAsync();
        _log.Information("Returning {result} with content body: {responseContent}.", result, responseContent);

        return result;
    }

在我的机器上,这可以按预期工作,并且在 301 重定向响应期间(其中 result.content 将为空),我得到 responseContent == null;但是,在同事的机器上,他在这一行收到了一个空引用异常。我们都使用 4.5.1 运行时,据我们所知的差异如下:

  • 我正在使用 VS2015 Enterprise SP2(它工作的地方),他正在使用 VS2015 Professional SP2(不起作用)

忍者编辑 - the .NET versions and service packs I have installed as well as the ones he has installed...

看起来它不工作的机器安装了两个我没有安装的 4.5.1 安全更新(KB2901126KB2931368),其中一个会导致这个问题吗?我需要检查的编译器或编译器选项是否存在差异?还是我在寻找解释更简单的东西?

【问题讨论】:

  • 您是否尝试过旧式空值检查?
  • 不同机器上的相同二进制文件..或另一个编译?如果是另一个编译,比较IL代码
  • 如果 result.Content 为 null,您将得到“await null”,这应该会抛出 NullReferenceException。您确定在您的情况下 result.Content 真的为空吗?

标签: c# .net c#-6.0 null-propagation-operator


【解决方案1】:

我不知道这两个机器有什么区别,但是你的代码是错误的:

await result.Content?.ReadAsStringAsync();

它的作用是,当result.Content 不是null 时,调用ReadAsStringAsync() 并且它的结果是awaited,这是应该的。但是当result.Contentnull时,整个子表达式result.Content?.ReadAsStringAsync()null,这意味着await会抛出一个NullReferenceException

因此,如果您想防止result.Content 成为null,您可能应该使用老式的if 或三元运算符。

【讨论】:

  • 啊。你说得对!谢谢你...我仍然需要弄清楚为什么“await null”不会在我的机器上引发异常,但会在我的同事机器上引发异常......或者我是否真的在我的机器上获取内容主体301重定向...无论哪种方式我仍然有问题,但这确实回答了这个特定的问题。
猜你喜欢
  • 2020-10-29
  • 2016-08-06
  • 2023-03-03
  • 2023-01-23
  • 2017-03-02
  • 2015-05-15
  • 2017-12-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多