[英]Why does trying to use string? (Nullable string) in C# produce a syntax error?
我有一個方法,如果郵政編碼無效,則返回null
如果有效則返回該string
。 它還在某些情況下轉換數據。
我在下面有以下單元測試但是我在使用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
約束 :
public struct Nullable<T> where T : struct
這將T
限制為不可為空的值類型。 這禁止您使用string
,因為System.String
是一個引用類型。
幸運的是, 由於 string是引用類型,因此您不需要使用Nullable<T>
- 它已經具有空值(空引用):
string x = null; // No problems here
string
已經是可以為空的類型了,不需要?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.