空条件运算符,在某些计算机上的行为不正常

时间:2016-05-13 20:08:11

标签: 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(不起作用)

Ninja Edit - the .NET versions and service packs I have installed as well as the ones he has installed ...

看起来它不工作的机器安装了两个4.5.1安全更新(KB2901126&amp; KB2931368),我不这样做,其中一个会导致此问题吗?我需要检查编译器或编译器选项是否有区别?或者我正在研究一些更简单的解释?

1 个答案:

答案 0 :(得分:3)

我不知道这两台机器之间的区别是什么,但是你的代码错了:

await result.Content?.ReadAsStringAsync();

这是做什么的,当result.Content不是null时,ReadAsStringAsync()被调用,其结果是await,就像它应该的那样。但是当result.Contentnull时,整个子表达式result.Content?.ReadAsStringAsync()null,这意味着await会抛出NullReferenceException

因此,如果您想要防止result.Content null if,您应该使用老式的function repeatString(s, count) { var result = ""; var num = 1; while ( num++ <= count ) { result += s; } return result; } 或三元运营商。