但是我尝试收到以下警告。
严重性代码 描述 项目文件行抑制状态 警告 CS8600 正在将 null 文字或可能的 null 值转换为不可为 null 的类型。
代码如下。
HttpResponseMessage response = await _httpClient.PutAsync(url, requestContent);
string? userResponse = await response.Content.ReadAsStringAsync();
JsonSerializerOptions? options = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
};
//if (userResponse.Length > 0)
//{
user = JsonSerializer.Deserialize<GetUserById>(userResponse, options);
//}
Run Code Online (Sandbox Code Playgroud)
我完全删除了 if 条件,但仍然收到警告。
按照建议添加了空检查。但仍然收到该警告。
nes*_*r11 10
JsonSerializer.Deserialize返回可为 null 的 GetUserById。您正在将可为空的值分配给不可为空的字段/属性。
您有两个选择:
这可以通过抛出空值异常来解决。user通过设置as GetUserById(not )的类型GetUserById?,您就声明它不能为 null,因此尽早抛出异常将是正确的选择。
GetUserById user =
JsonSerializer.Deserialize<GetUserById>(userResponse, options) ??
throw new InvalidOperationException();
Run Code Online (Sandbox Code Playgroud)
请注意,JsonSerializer.Deserialize当字符串 equals 时,在特殊情况下返回 null "null"。请参阅/sf/answers/5059561601/。
从 C# 8 开始,您还可以使用null-forgiving 运算符。通常不建议这样做,因为如果值碰巧为 null,它会使程序稍后失败。
GetUserById user = JsonSerializer.Deserialize<GetUserById>(userResponse, options)!;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18580 次 |
| 最近记录: |