在 C# 中,值类型的值不能为 null,但是您可以通过附加问号来启用它。
例如
int intCannotBeNull = 1;
int? intCanBeNull = null;
此外,在 C# 中,许多值类型都有 static 成员,因此您可以这样做,例如:
string strValue = "123";
intCannotBeNull = int.Parse(strValue);
但是您不能执行以下任一操作:
intCanBeNull = int?.Parse(strValue);
intCanBeNull = (int?).Parse(strValue);
C# 很困惑。是否有一个有效的语法意味着 strValue 可以是 null 或一个有效的整数值并使赋值有效?
我知道有一些简单的解决方法,例如:
intCanBeNull = (strValue == null) ? null : (int?)int.Parse(strValue);
和同一事物的其他变体,但那只是一团糟......
请您参考如下方法:
int?是 Nullable<int> 的语法糖.你问的是 Nullable<int>.Parse .没有这样的方法。这就是您的困惑所在。
