【发布时间】:2010-09-07 21:16:28
【问题描述】:
我想在 C# 中将字符串解析为可为空的 int。 IE。如果无法解析,我想取回字符串的 int 值或 null。
我有点希望这会奏效
int? val = stringVal as int?;
但这行不通,所以我现在这样做的方式是我已经编写了这个扩展方法
public static int? ParseNullableInt(this string value)
{
if (value == null || value.Trim() == string.Empty)
{
return null;
}
else
{
try
{
return int.Parse(value);
}
catch
{
return null;
}
}
}
有更好的方法吗?
编辑:感谢 TryParse 的建议,我确实知道这一点,但结果大致相同。我更想知道是否有内置的框架方法可以直接解析为可为空的 int?
【问题讨论】:
-
您可以使用 string.IsNullOrEmpty(value) 使 if 行更清晰。
标签: c# .net string .net-3.5 nullable