简体   繁体   English

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

[英]Why does trying to use string? (Nullable string) in C# produce a syntax error?

I have a method that returns null if the postcode is invalid, and just returns the string if it is valid. 我有一个方法,如果邮政编码无效,则返回null如果有效则返回该string It also transforms the data in certain cases. 它还在某些情况下转换数据。

I have the following unit test below but I am getting syntax errors on the lines where it is using string? 我在下面有以下单元测试但是我在使用string?的行上遇到语法错误string? . Could anyone tell me why? 谁能告诉我为什么?

    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);
    }

The ? ? suffix on the name of a type is an alias for using Nullable<T> (section 4.1.10 of the C# 4 spec). 类型名称的后缀是使用Nullable<T>的别名(C#4规范的第4.1.10节)。 The type parameter for Nullable<T> has the struct constraint : Nullable<T>的类型参数具有struct约束

public struct Nullable<T> where T : struct

This constrains T to be a non-nullable value type. 这将T限制为不可为空的值类型。 That prohibits you from using string , as System.String is a reference type. 这禁止您使用string ,因为System.String是一个引用类型。

Fortunately, as string is a reference type, you don't need to use Nullable<T> - it already has a null value (the null reference): 幸运的是, 由于 string是引用类型,因此您不需要使用Nullable<T> - 它已经具有空值(空引用):

string x = null; // No problems here

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM