这个Decimal.TryParse出了什么问题?

时间:2012-12-14 11:04:29

标签: c# tryparse

代码:

Decimal kilometro = Decimal.TryParse(myRow[0].ToString(), out decimal 0);

某些论据无效?

4 个答案:

答案 0 :(得分:27)

out decimal 0不是有效参数 - 0不是有效的变量名。

decimal output;
kilometro = decimal.TryParse(myRow[0].ToString(), out output);

顺便说一句,返回值将是bool - 从变量名称开始,您的代码应该是:

if(decimal.TryParse(myRow[0].ToString(), out kilometro))
{ 
  // success - can use kilometro
}

由于您想要返回kilometro,您可以执行以下操作:

decimal kilometro = 0.0; // Not strictly required, as the default value is 0.0
decimal.TryParse(myRow[0].ToString(), out kilometro);

return kilometro;

答案 1 :(得分:4)

好吧,decimal.TryParse会返回bool类型 - 因此您需要执行以下操作:

Decimal kilometro;

// if .TryParse is successful - you'll have the value in "kilometro"
if (!Decimal.TryParse(myRow[0].ToString(), out kilometro)
{ 
   // if .TryParse fails - set the value for "kilometro" to 0.0
   kilometro = 0.0m;
} 

答案 2 :(得分:2)

下面给出了TryParse语句的正确用法。 您必须先声明小数,然后将其传递给TryParse方法。如果TryParse成功,kilometro将是新值,否则它将为零。我相信这是你想要的结果。

decimal kilometro = 0;
if (Decimal.TryParse(myRow[0].ToString(), out kilometro))
{
   //The row contained a decimal.
}
else {
   //The row could not be parsed as a decimal.
}

答案 3 :(得分:0)

作为附加答案,您现在可以内联声明参数。

if (decimal.TryParse(myRow[0].ToString(), out decimal outParamName))
{
    // do stuff with decimal outParamName
}