Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# int.TryParse之前的Nullcheck_C#_Int - Fatal编程技术网

C# int.TryParse之前的Nullcheck

C# int.TryParse之前的Nullcheck,c#,int,C#,Int,我有很多字符串被解析成整数值的代码 string item = null; //or a value int result; if (!string.IsNullOrEmpty(item) && int.TryParse(item, out result)) { //do stuff } 是否每次都需要检查IsNullOrEmpty?如果为null或为空,则解析应失败。Int.TryParse将返回布尔值(true,如果成功),因此您可以编写: string item

我有很多字符串被解析成整数值的代码

string item = null; //or a value
int result;
if (!string.IsNullOrEmpty(item) && int.TryParse(item, out result))
{
    //do stuff
}

是否每次都需要检查
IsNullOrEmpty
?如果为
null
或为空,则解析应失败。

Int.TryParse
将返回布尔值(
true
,如果成功),因此您可以编写:

string item = null; //or a value
int result;
if (int.TryParse(item, out result))
{
    //do stuff
}

否,
String.IsNullOrEmpty
在这里是多余的,因为它通过返回
false
来处理这种情况。所以这更简洁:

int result;
if (int.TryParse(item, out result))
{
    //do stuff
}
MSDN:

如果s参数为null或String,转换失败。空的是 格式不正确,或表示的数字小于MinValue 或大于MaxValue


如果您使用
.TryParse
进行转换,则无需检查null或empty。因为,如果转换失败,返回值将为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
然后。如果尝试解析失败,结果将为0。@TimSchmelter可以这样做,但这种机械的turk方法允许使用fire-and-forget方式解决问题。花同样的时间快速提出一个问题,去吃午饭,回到答案上来——有几个词描述了这种现象,但它们主要是基于观点;-)@Adamhuldsworth停止拖拉,这不会增加任何价值here@TimSchmelter必须有此检查的原因。它是否因为
TryParse
不是一个简单的方法而提高了性能,并且通过之前检查
null
,可以提高应用程序的性能?如前所述,代码中有许多这样的检查