cannot convert from 'out double?' to 'out double'
I have the following section of code in an app that I am writing:
...
String[] Columns = Regex.Split(CurrentLine, Delimeter);
Nullable<Double> AltFrom;
...
if (AltFrom == null)
{
Double.TryParse(Columns[LatIndex].Trim(), out AltFrom);
}
...
The line in the if clause wil开发者_运维问答l not compile and shows the error: cannot convert from 'out double?' to 'out double'
if I don't make AltFrom a Nullable type and rather explicitly state it as a Double, everything is happy.
Surely this is valid code. Is this just a bug in c# or am I doing something wrong?
No the out parameter really needs to be a double, not a Nullable<double>.
double? altFrom = null;
double temp = 0;
if (double.TryParse( Columns[LatIndex].Trim(), out temp))
{
altFrom = temp;
}
First, you can not implicitly convert a double? to a double. The reason is because what would be the value of the double if the double? represented the null value (i.e., value.HasValue is false)? That is, converting from a double? to a double results in a loss of information (it is a narrowing conversion). Implicit narrowing conversions are generally frowned upon in the framework.
But actually, the problem that you are seeing here is something different. When you have a method that accepts an out parameter of type T, you must pass in a variable of type T; there can not be any type variation in this case as there is with non-ref and non-out parameters.
To get around your problem, use the following:
if (AltFrom == null) {
double value;
Double.TryParse(Columns[LatIndex].Trim(), out value);
AltFrom = value;
}
加载中,请稍侯......
精彩评论