我有一些代码需要将许多字符串解析为整数值。
string item = null; //or a value
int result;
if (!string.IsNullOrEmpty(item) && int.TryParse(item, out result))
{
//do stuff
}
每次都需要检查IsNullOrEmpty
吗?如果是null
或空,那么解析应该失败。
不需要使用String.IsNullOrEmpty
,因为Int32.TryParse
会返回false
。因此以下代码更加简洁:
int result;
if (int.TryParse(item, out result))
{
//do stuff
}
MSDN:
如果 s 参数为 null 或空字符串 String.Empty,或者不符合正确的格式或表示的数字小于 MinValue 或大于 MaxValue,则转换失败。
Int.TryParse
会返回一个布尔值(如果它成功,则为true
),因此您可以编写:
string item = null; //or a value
int result;
if (int.TryParse(item, out result))
{
//do stuff
}
如果您使用.TryParse
进行转换,则无需检查空或空字符串。由于如果转换失败,返回值将为false。因此,可以像这样安全地使用:
string item = null; //or a value
int result;
if(int.TryParse(item, out result))
{
//do stuff
}
else
{
// you can show conversion failure message here
// or can proceed with value 0
}
附加说明:如果您正在使用int.Parse
进行转换,则最好检查string.IsNullOrEmpty
,因为null
会导致ArgumentNullException
,而空字符串会导致FormatException
。
TryParse
返回false
,则表示测试未通过。 - Tim SchmelterIsNullOrEmpty
检查的原因。是否因为TryParse
不是一个简单的方法,通过在之前检查null
,可以提高应用程序性能?如之前所述,在代码中有很多此类检查。 - Toshiint.TryParse
可以处理它。事实上,它首先处理了空值情况,所以没有性能差异。 - Tim Schmelter