【问题标题】:Warning CS8600 Converting null literal or possible null value to non-nullable type警告 CS8600 将 null 文字或可能的 null 值转换为不可为 null 的类型
【发布时间】:2022-02-18 17:25:51
【问题描述】:

但是我尝试收到以下警告。

严重性代码描述项目文件行抑制状态 警告 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);
//}

看了thisthis之类的帖子,不知道怎么解决。

更新。

我完全删除了 if 条件,但仍然收到警告。

更新 2

按照建议添加了空检查。但仍然收到该警告。

【问题讨论】:

  • 您应该在检查长度之前检查 userResponse 是否为空
  • 您在哪一行收到警告?
  • 在下面查看我的答案。我在代码示例中添加了您缺少的空检查。
  • 你必须使用你的字符串作为“字符串”吗? ? "string userResponse" 仍然可以为空,你不必使用 "string?" 来指定它

标签: c# c#-10.0


【解决方案1】:

JsonSerializer.Deserialize 返回可为空的 GetUserById。您正在将可为空的值分配给不可为空的字段/属性。

你有两个选择:

【讨论】:

    【解决方案2】:

    我相信这是在警告您 userResponse 为 null 并且需要检查它是否为 null 状态。如果你做一个空检查,警告应该消失。

    为您执行 userResponse.Length 试试这个:

    HttpResponseMessage response = await _httpClient.PutAsync(url, requestContent);
    var userResponse = (string?)null;
    userResponse = await response.Content.ReadAsStringAsync();
    JsonSerializerOptions? options = new JsonSerializerOptions
    {
      PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
    };
    
    if (userResponse != null)
    {
      user = JsonSerializer.Deserialize<GetUserById>(userResponse, options);
    }
    

    【讨论】:

    • 尝试了以下方法(添加 ! 到参数中)。但仍然收到警告。 user = JsonSerializer.Deserialize(userResponse!, options!);
    • 您需要进行实际的 NULL 检查。不是说它可以为空。我会更新代码。
    • 仍然收到警告。查看我的更新
    • 它抱怨的行号是什么,您能在示例中指出该行吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-09
    • 2016-10-23
    • 1970-01-01
    相关资源
    最近更新 更多