c# - 将 null 文字或可能的 null 值转换为不可为 null 的类型,尽管有 null 合并运算符

标签 c# compiler-warnings nullable .net-7.0

我对 C# 还很陌生(大约 4 个月),我不明白为什么这会成为一个问题。

Run on DotNet Fiddle

#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 C# documentation具体说:

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 conversionstringJsonNode? 并且编译器不理解结果值始终不为 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/

相关文章:

c# - FileHelperEngine 构造函数 - InvalidcastException

html - 在 Less 中使用变量之后而不是之前定义变量可以吗?

c# - 可空类型到底什么时候抛出异常?

sql - 我应该对 NOT NULL 列有多自由?

c# - EF7 使用 SQLite 生成错误的迁移

c# - SQL数据源参数

c++ - `push_back` 与 `emplace_back` 标志警告

java - 仅当变量为空时才在 Kotlin 中实例化变量?

c# - OpenFileDialog - InitialDirectory 打开一个远程目录

objective-c - 使 Xcode 4.3 警告当前 @implementation 中存在的未声明方法