gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 21:49:04 28 4
gpt4 key购买 nike

我在 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(可用的地方),他使用的是 VS2015Professional 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() 并且其结果是 awaited,这是应该的。但是当result.Contentnull时,整个子表达式result.Content?.ReadAsStringAsync()null,这意味着 await 将抛出一个 NullReferenceException

所以,如果你想防止 result.Contentnull,你可能应该使用老式的 if 或三元运营商。

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

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com