可为空的静态成员
本文关键字:静态成员 | 更新日期: 2023-09-27 18:33:36
在 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
.没有这样的方法。这就是你的困惑所在。
Parse
不会处理null
值,它会抛出异常。您必须使用 TryParse 或 Convert 类来解析
Convert.ToInt32(int or int?)
这适用于长整型、浮点型、十进制等。
int?
实际上是Nullable<int>
。该Nullable<T>
结构没有 T
类的方法。因此,您必须自己做。
在 int?
的情况下,您可以尝试这样的事情:
string s = "1";
int? result;
if (string.IsNullOrEmpty(s))
{
result = null;
}
else
{
int o; // just a temp variable for the `TryParse` call
if (int.TryParse(s, out o))
{
result = o;
}
else
{
result = null;
}
}
// use result