C# 这个 Decimal.TryParse 有什么问题?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13877405/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is wrong on this Decimal.TryParse?
提问by markzzz
Code :
代码 :
Decimal kilometro = Decimal.TryParse(myRow[0].ToString(), out decimal 0);
some arguments are not valid?
有些论点是无效的?
采纳答案by Oded
out decimal 0is not a valid parameter - 0is not a valid variable name.
out decimal 0不是有效的参数 -0不是有效的变量名称。
decimal output;
kilometro = decimal.TryParse(myRow[0].ToString(), out output);
By the way, the return value will be a bool- from the name of the variable, your code should probably be:
顺便说一句,返回值将是bool- 从变量的名称,您的代码应该是:
if(decimal.TryParse(myRow[0].ToString(), out kilometro))
{
// success - can use kilometro
}
Since you want to return kilometro, you can do:
既然你想 return kilometro,你可以这样做:
decimal kilometro = 0.0; // Not strictly required, as the default value is 0.0
decimal.TryParse(myRow[0].ToString(), out kilometro);
return kilometro;
回答by marc_s
Well, the decimal.TryParsereturns a booltype - so you need to do something like:
好吧,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;
}
回答by jaypeagi
The correct usage of the TryParse statement is given below.
You must declare the decimal first and then pass it into the TryParse method. If the TryParse succeeds, kilometrowill be the new value, otherwise it will be zero. I believe that was your desired outcome.
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.
}
回答by azurez27
Just as an additional answer, you can now declare out parameters inline.
作为额外的答案,您现在可以内联声明参数。
if (decimal.TryParse(myRow[0].ToString(), out decimal outParamName))
{
// do stuff with decimal outParamName
}

