【问题标题】:Null-forgiving operator (!) not working in C# >= 8.0Null-forgiving 运算符 (!) 在 C# >= 8.0 中不起作用
【发布时间】: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

有什么想法可以让第二个工作正常吗?

【问题讨论】:

标签: c# c#-8.0


【解决方案1】:

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

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

【讨论】:

  • 感谢学习这种新语法,为演员节省了一行!
【解决方案2】:

null-forgiving operator(Damn it) 运算符允许您通知编译器它应该忽略可能为 null 的引用,因为您比编译器拥有更多的信息。

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

null-forgiving operator 直到 C# 8.0 才实现,您需要一个 nuget 包或一些替代解决方法才能在 C#7.3 的上下文中启用爆炸符号。

有什么想法可以让第二个工作正常吗?

当使用Nullable<T>struct 时,您可以使用.Value 属性来获取对象的值(您定义的实际Person struct)。如果没有.Value 方法,编译器将不知道您是在尝试访问您定义的Nullable<T> 对象还是struct 对象。所以在Nullable<T>对象上找不到.name字段。

这应该适合你

if (person != null) Console.WriteLine("name: " + person!.Value.name);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-07
    • 2017-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-30
    • 2022-12-15
    相关资源
    最近更新 更多