简体   繁体   中英

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. 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? . 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). The type parameter for Nullable<T> has the struct constraint :

public struct Nullable<T> where T : struct

This constrains T to be a non-nullable value type. That prohibits you from using string , as System.String is a reference type.

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 x = null; // No problems here

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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