簡體   English   中英

這個 Decimal.TryParse 有什么問題?

[英]What is wrong on this Decimal.TryParse?

代碼:

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

有些論點無效?

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;

那么, 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;
} 

下面給出了 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.
}

作為附加答案,您現在可以內聯聲明參數。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM