空条件运算符,在某些机器上表现不正常 [英] Null Conditional Operator, not behaving as expected on some machines

查看:51
本文介绍了空条件运算符,在某些机器上表现不正常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following code in a DelegatingHandler for a WebApi 2 project.

    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运行时,据我们所知,差异如下:

On my machine this works as expected and during a response that is a 301 Redirect (where result.content would be null) I get responseContent == null; however, on a co-workers machine he receives a null reference exception on this line. We are both using the 4.5.1 runtime, the differences as far as we can tell is as follows follows:

  • 我正在使用VS2015 Enterprise SP2(在可以运行的地方),他正在使用VS2015专业SP2(无法正常工作)

Ninja Edit-我已安装以及他已安装的.NET版本和Service Pack ...

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

看起来它无法正常运行的计算机已安装了两个4.5.1安全更新( KB2901126 KB2931368 ),我不会这些会导致此问题吗?我需要检查的编译器或编译器选项是否有所不同?还是我正在寻找更简单的解释?

It looks like the machine where it is not working has two 4.5.1 security updates installed (KB2901126 & KB2931368) that I do not, would one of these cause this issue? Is there a difference in the compilers or compiler options that I need to check? Or am I looking into something that has a simpler explanation?

推荐答案

我不知道两台计算机之间的区别是什么,但是您的代码是错误的:

I don't know what the difference between the two machines is, but your code is wrong:

await result.Content?.ReadAsStringAsync();

这是什么,当 result.Content 不是 null 时,将调用 ReadAsStringAsync(),其结果是等待,因为它应该.但是,当 result.Content null 时,整个子表达式 result.Content?.ReadAsStringAsync() null ,这意味着 await 将抛出 NullReferenceException .

What this does, is that when result.Content is not null, ReadAsStringAsync() is called and its result is awaited, as it should. But when result.Content is null, the whole subexpression result.Content?.ReadAsStringAsync() is null, which means that the await will throw a NullReferenceException.

因此,如果要防止 result.Content null ,则应该使用老式的 if 或三元运算符.

So, if you want to protect against result.Content being null, you should probably use an old-fashioned if or a ternary operator.

这篇关于空条件运算符,在某些机器上表现不正常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆