我尝试在 Unity 2020.3.1f1 中与 vscode 一起使用这个 null-forgiving 运算符 (!)。这些工具都没有看到这种语法的工作原理,所以我将其复制到这两个受文档启发的小提琴中: https:
//learn.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);
}
}
Run Code Online (Sandbox Code Playgroud)
首先,C# 7.3 未按预期工作: https: //dotnetfiddle.net/HMS35M
其次,C# 8.0 至少忽略了看起来的语法: https: //dotnetfiddle.net/Mhbqhk
有什么想法可以让第二个发挥作用吗?
空值宽容运算符不适用于Nullable<T>- 唯一可用的相关成员仍然是.Value,.HasValue和.GetValueOrDefault(); 您必须使用稍长的person.Value.name/ person.GetValueOrDefault().name,或者您可以在测试期间捕获该值if:
if (person is Person val) Console.WriteLine("name: " + val.name);
Run Code Online (Sandbox Code Playgroud)