我有一个方法,如果邮政编码无效则返回 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);
}
最佳答案
?
类型名称的后缀是使用 Nullable<T>
的别名(C# 4 规范的第 4.1.10 节)。 Nullable<T>
的类型参数有 struct
constraint :
public struct Nullable<T> where T : struct
这限制了 T
成为不可为 null 的值类型。这禁止您使用 string
, 作为 System.String
是引用类型。
幸运的是,因为字符串是引用类型,你不需要使用Nullable<T>
- 它已经有一个空值(空引用):
string x = null; // No problems here
关于c# - 为什么要尝试使用字符串? C# 中的(可空字符串)产生语法错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8577770/