c# - 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
任何想法使第二个工作?
解决方案
null-forgiving 运算符不适用于Nullable<T>
- 唯一可用的相关成员仍然存在.Value
,.HasValue
并且.GetValueOrDefault()
; 您将不得不使用稍长的person.Value.name
/ person.GetValueOrDefault().name
,或者您可以在测试期间捕获该值if
:
if (person is Person val) Console.WriteLine("name: " + val.name);
推荐阅读
- r - dplyr::select 语义为 cross(),选择范围 a:n 中的列,然后在一个中排除
- python - 从 BeautifulSoup 中的 span 标签中提取数据内容
- python - Python语音识别麦克风无法识别语音
- android - Paypal SDK 与 Android 登录集成失败
- vb.net - 从 Windows 窗体上的复选框中删除检查状态
- elixir - live_redirect 表单后不抛出 phx-change
- javascript - 使用模板组件的搜索过滤器问题
- excel - 使用 + 连接时类型不匹配
- docker - 如何在 Docker Swarm 中解析全局部署服务的本地到节点实例(任务)的 IP
- javascript - 如何在用户类型时自动滑动 React Native TextInput Carousel