【发布时间】:2021-05-19 11:56:47
【问题描述】:
我尝试在 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
有什么想法可以让第二个工作正常吗?
【问题讨论】:
-
它工作正常。 在问题本身中发布您的代码
-
@PanagiotisKanavos 完成
-
@HansKilian 首先通过消息很明显,其次是 8 或 9 之后:docs.microsoft.com/en-us/dotnet/csharp/language-reference/…