C# mono的可为null变量如何处理?

我写了如下代码:

using System;

class Program {

    static int n, m;
    static int[]? f = null;

    static int find(int x) {
        if (f![x] == x) return x;
        return f[x] = find(f[x]);
    }

    static void merge(int x, int y) {
        x = find(x);
        y = find(y);
        if (x != y) f![x] = y;
    }

    static void Main(String[] args) {
    }
}

f 在定义时是 null,在 Main 中分配 f = new int[n + 1];

但是这段代码在 洛谷IDE 中的C# mono中无法编译通过。

报错如下

/tmp/compiler_hlxsun_w/src(16,17): error CS1519: Unexpected symbol `?' in class, struct, or interface member declaration
/tmp/compiler_hlxsun_w/src(16,21): error CS1519: Unexpected symbol `=' in class, struct, or interface member declaration
/tmp/compiler_hlxsun_w/src(19,13): error CS1525: Unexpected symbol `!'
/tmp/compiler_hlxsun_w/src(19,14): error CS1525: Unexpected symbol `['
/tmp/compiler_hlxsun_w/src(26,21): error CS1525: Unexpected symbol `!'
/tmp/compiler_hlxsun_w/src(26,22): warning CS0642: Possible mistaken empty statement
/tmp/compiler_hlxsun_w/src(26,22): error CS1525: Unexpected symbol `['
Compilation failed: 6 error(s), 1 warnings

我查阅了一些资料也没有什么发现,想请问有没有C# mono的相关资料?或者这部分应该如何写在visual studio 的C
#和C# mono中都没有warning和error?

查看下版本是多少

img

该回答引用ChatGPT

首先,上面的代码是 C# 8.0 中的可空引用类型的语法,也就是使用 ? 和 ! 符号来表示一个值类型或引用类型是否可以为 null。这个语法需要在编译器中开启才能使用,否则会出现上述错误。

对于上述报错,可以尝试以下几点来解决:

确认使用的编译器版本是否支持 C# 8.0 的可空引用类型语法,如果不支持,则需要使用传统的 null 检查语法。

如果编译器版本支持 C# 8.0 的可空引用类型语法,可以尝试在代码文件的头部添加以下语句来启用:

#nullable enable

可以尝试将 ? 和 ! 符号改为传统的 null 检查语法,例如:


if (f == null) throw new ArgumentNullException(nameof(f));
if (f[x] == null) throw new ArgumentNullException(nameof(f[x]));
if (f[x] == x) return x;
return f[x] = find(f[x]);

如果上述方法都不行,可以考虑升级编译器版本或切换到其他支持 C# 8.0 的编译器。

要看.net framework版本
低版本不支持可空类型
此外,你确定是要定义int[]?而不是int?[]
数组本身是引用类型,它本来就可以是空,不需要加问号