如何使用int.TryParse可空INT?

如何使用int.TryParse可空INT?

问题描述:

我想使用的TryParse找到,如果该字符串值是一个整数。如果该值是一个整数,然后跳过foreach循环。这里是我的代码。

I am trying to use TryParse to find if the string value is an integer. If the value is an integer then skip foreach loop. Here is my code.

string strValue = "42 "

 if (int.TryParse(trim(strValue) , intVal)) == false
 {
    break;
 }



INTVAL是一个int类型的变量?(可空INT)。 ?我如何使用的TryParse可空INT

intVal is a variable of type int?(nullable INT). How can I use Tryparse with nullable int?

而无需使用另外一个变量,可惜你不能做到这一点 - 因为类型的退出参数具有参数完全匹配。

You can't do this without using another variable, unfortunately - because the type of out arguments has to match the parameter exactly.

像丹尼尔的代码,但固定在第二个参数方面,修剪,并避免与布尔常量的比较:

Like Daniel's code, but fixed in terms of the second argument, trimming, and avoiding comparisons with Boolean constants:

int tmp;
if (!int.TryParse(strValue.Trim(), out tmp))
{
    break;
}
intVal = tmp;