English 中文(简体)
Resharper 陷阱「转换为返回语句」。
原标题:
  • 时间:2009-03-09 17:17:23
  •  标签:

鉴于以下例程:

private static object ParseNumber(string token, FieldDefinition def)
{
  if (def.Fraction > 0)
    return Double.Parse(token);
  else
    return Int64.Parse(token);
}

Resharper提供了一种选项,使用三元运算符将其重构为语句。

private static object ParseNumber(string token, FieldDefinition def)
{
  return def.Fraction > 0 ? Double.Parse(token) : Int64.Parse(token);
}

谁能发现陷阱?

最佳回答

好的,更改为先前的答案。因为从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

这取决于YZ的类型,我会称之为TYTZ。有几个选择:

  • 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?)

问题回答

暂无回答




相关问题
热门标签