好的,更改为先前的答案。因为从Int64
转换为Double
存在隐式转换(但反过来不行),因此将是表达式的结果类型。因此,当您希望获得包装的Int64
时,实际上会获得一个包装的Double
(但其值最初来自Int64.Parse
)。
以防不清楚,让我们更改所有的return
语句,使它们仅返回一个变量。 这是原始代码:
private static object ParseNumber(string token, FieldDefinition def)
{
if (def.Fraction > 0)
return Double.Parse(token);
else
return Int64.Parse(token);
}
请适当转换。
private static object ParseNumber(string token, FieldDefinition def)
{
if (def.Fraction > 0)
{
double d = Double.Parse(token);
object boxed = d; // Result is a boxed Double
return boxed;
}
else
{
long l = Int64.Parse(token);
object boxed = l; // Result is a boxed Int64
return boxed;
}
}
现在让我们对于使用条件运算符的版本做同样的事情:
private static object ParseNumber(string token, FieldDefinition def)
{
return def.Fraction > 0 ? Double.Parse(token) : Int64.Parse(token);
}
成为
private static object ParseNumber(string token, FieldDefinition def)
{
// The Int64.Parse branch will implicitly convert to Double
double d = def.Fraction > 0 ? Double.Parse(token) : Int64.Parse(token);
object boxed = d; // *Always* a Double
return boxed;
}
EDIT:如要求,再提供一点信息。形式为的条件表达式的类型:
X ? Y : Z
这取决于Y
和Z
的类型,我会称之为TY
和TZ
。有几个选择:
TY
and TZ
are the same type: result is that type
- There s an implicit conversion from
TY
to TZ
but not from TZ
to TY
: the result is of type TZ
and the conversion is used if the first branch is used.
- There s an implicit conversion from
TZ
to TY
but not from TY
to TZ
: the result is of type TY
and the conversion is used if the second branch is used.
- There s an implicit conversion in both directions: compile-time error
- There are no conversions either way: compile-time error
那有帮助吗? (nà yǒu bāng zhù ma?)