我对 C# 还很陌生(大约 4 个月),我不明白为什么这会成为一个问题。
#nullable enable
using System;
using System.Text.Json;
using System.Text.Json.Nodes;
public class Test{
public static void Main(){
var json = @"{""key"": ""value""}";
var node = JsonSerializer.Deserialize<JsonObject>(json);
if( node is null ){
return;
}
foreach( var property in node ){
var key = property.Key;
var val = (string) (property.Value?? "" ); // warning
Console.WriteLine($"{key}: {val}");
}
}
}
线路
var val = (string) (property.Value?? "" );
发出警告
Converting null literal or possible null value to non-nullable type.
The null-coalescing operator ?? returns the value of its left-hand operand if it isn't null; otherwise, it evaluates the right-hand operand and returns its result. The ?? operator doesn't evaluate its right-hand operand if the left-hand operand evaluates to non-null.
这让我得出结论,括号的内容 property.Value?? ""
永远不能为空。然而,该警告似乎表明并非如此。
这是一个错误还是我误解了什么?
最佳答案
根据您的目标,您可以使用:
var val = property.Value?.ToString() ?? "" ;
或者
var val = property.Value?.ToJsonString() ?? "" ;
警告的问题似乎是 property.Value?? ""
内部使用 implicit conversion从 string
到 JsonNode?
并且编译器不理解结果值始终不为 null ( source code )。我认为它可以在 .NET 8 中修复,并用相应的属性进行标记:
[return: NotNullIfNotNull(nameof(value))]
public static implicit operator JsonNode?(string? value) => JsonValue.Create(value);
关于c# - 将 null 文字或可能的 null 值转换为不可为 null 的类型,尽管有 null 合并运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76668598/