首页 > 解决方案 > Null-forgiving 运算符 (!) 在 C# >= 8.0 中不起作用

问题描述

我尝试在 Unity 2020.3.1f1 和 vscode 中使用这个容错运算符 (!)。这些工具都没有看到这种语法工作,所以我将它复制到这两个受文档启发的小提琴中:
https ://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-forgiving

两者的代码相同:

using System;

public class Program
{
    #nullable enable
    public struct Person {
        public string name;
    }
    
    static Person? GetPerson(bool yes) {
        Person ret = new Person();
        ret.name = "coucou";
        if(yes) return ret;
        else return null;
    }
    
    public static void Main()
    {
        Person? person = GetPerson(true);
        if(person != null) Console.WriteLine("name: " + person!.name);
    }
}

首先使用 C# 7.3 无法按预期工作: https ://dotnetfiddle.net/HMS35M

其次,C# 8.0 至少忽略了它看起来的语法:https ://dotnetfiddle.net/Mhbqhk

任何想法使第二个工作?

标签: c#c#-8.0

解决方案


null-forgiving 运算符不适用于Nullable<T>- 唯一可用的相关成员仍然存在.Value.HasValue并且.GetValueOrDefault(); 您将不得不使用稍长的person.Value.name/ person.GetValueOrDefault().name,或者您可以在测试期间捕获该值if

if (person is Person val) Console.WriteLine("name: " + val.name);

推荐阅读