[英]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.