c# - 为什么要尝试使用字符串? C# 中的(可空字符串)产生语法错误?

标签 c# .net string nullable

我有一个方法,如果邮政编码无效则返回 null,如果有效则返回 string。在某些情况下,它还会转换数据。

我在下面进行了以下单元测试,但在使用 string? 的行中出现语法错误。谁能告诉我为什么?

    public void IsValidUkPostcodeTest_ValidPostcode()
    {
        MockSyntaxValidator target = new MockSyntaxValidator("", 0);
        string fieldValue = "BB1 1BB";
        string fieldName = "";
        int lineNumber = 0;
        string? expected = "BB1 1BB"; 
        string? actual;

        actual = target.IsValidUkPostcode(fieldValue, fieldName, lineNumber);

        Assert.AreEqual(expected, actual);
    }

最佳答案

?类型名称的后缀是使用 Nullable<T> 的别名(C# 4 规范的第 4.1.10 节)。 Nullable<T> 的类型参数有 struct constraint :

public struct Nullable<T> where T : struct

这限制了 T成为不可为 null 的值类型。这禁止您使用 string , 作为 System.String是引用类型。

幸运的是,因为字符串是引用类型,你不需要使用Nullable<T> - 它已经有一个空值(空引用):

string x = null; // No problems here

关于c# - 为什么要尝试使用字符串? C# 中的(可空字符串)产生语法错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8577770/

相关文章:

c# - 从 XML 中删除出现的标记

string - 在 Bash 中比较两个字符串时出现 "command not found"错误

c# - 正则表达式 - 如何制作前瞻模式

c# - C# 2.0 中的接口(interface)多态性

.net - 是否可以将 Windows Mobile 仿真构建到应用程序中?

java - 在java中获取zip文件夹中的文件作为字符串

python - 基于正则表达式拆分字符串而不消耗字符

c# - 分别获取位图图像中黑白像素的总数

c# - 使用 Moq 调用方法时如何验证上下文条件

.net - 通过组策略部署 VSTOR 4 框架 MSI