c# - 空条件运算符,在某些机器上的行为不符合预期

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

我在 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 将为 null),我得到 responseContent == null;然而,在同事的机器上,他在这一行收到空引用异常。我们都使用4.5.1运行时,据我们所知,差异如下:

  • 我使用的是 VS2015 Enterprise SP2(可以使用),他使用的是 VS2015 专业 SP2(不起作用的地方)

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

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

最佳答案

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

await result.Content?.ReadAsStringAsync();

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

所以,如果您想防范 result.Contentnull ,你可能应该使用老式的 if或三元运算符。

关于c# - 空条件运算符,在某些机器上的行为不符合预期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37218581/

相关文章:

c# - 如何将 msbuild 升级到 C# 6?

c# - 在 for 循环中随机生成一个 int 值。 7 次迭代后,它返回一个非常大的负数。为什么是这样?

C# Moq 如何获取所有方法调用

c# - 如何用更少的代码行简洁地将 List<T> 中的值提取到 M x 1 double[,] 数组中?

c# - C# 窗体程序中的 "Specified cast is not valid"错误

c# - 什么可能是我的 C# WCF 服务上的速率限制 CPU 周期?

c# - 如何检查文件夹的可访问性?

.net - 全局覆盖特定文化的所有实例的月份名称

c# - 将 Json 文档反序列化为 C# 对象

c# - C# 6.0 中的只读属性