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

edi*_*ode 10 .net c# 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);
    }
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 14

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

public struct Nullable<T> where T : struct
Run Code Online (Sandbox Code Playgroud)

这约束T为不可为空的值类型.这禁止您使用string,作为System.String参考类型.

幸运的是,由于 string是引用类型,因此您不需要使用Nullable<T>它 - 它已经具有空值(空引用):

string x = null; // No problems here
Run Code Online (Sandbox Code Playgroud)


Sha*_*ake 6

string 已经是可以为空的类型,不需要了 ?