【问题标题】:Ternary operator not working correctly with Vector3三元运算符无法与 Vector3 一起正常工作
【发布时间】:2014-04-29 21:56:04
【问题描述】:

我这里有两个代码 sn-ps,第一个产生错误,但第二个有效。为什么?

public static Vector3? GetRayPlaneIntersectionPoint(Ray ray, Plane plane)
{
    float? distance = ray.Intersects(plane);
    return distance.HasValue ? ray.Position + ray.Direction * distance.Value : null;
}

Give:无法确定条件表达式的类型,因为 '' 和 'Microsoft.Xna.Framework.Vector3' 之间没有隐式转换

但是下面没有三元运算符的 sn-p 工作得很好。

public static Vector3? GetRayPlaneIntersectionPoint(Ray ray, Plane plane)
{
    float? distance = ray.Intersects(plane);

    if (distance.HasValue)
        return ray.Position + ray.Direction * distance.Value;
    else
        return null;
}

【问题讨论】:

  • 这个问题在这个网站上已经被问了数百次了。 C# 语言要求从 insideoutside 计算表达式。转换为可空类型outside 并不影响如何分析表达式的inside;相反,它恰恰相反。一旦确定了表达式内部的类型,就将其与外部的类型进行比较,看是否兼容。
  • 猜猜有一个很大的误解,条件表达式应该是一样的,而三元运算符更像是语法糖。
  • 您提出了一个有效的观点。数百人或更可能数千人对此感到困惑,这一事实表明操作员的设计可能存在缺陷。或者,另一种思考方式:规则是明智的,但错误信息可能更清楚。它可以说“条件运算符的结果和替代必须具有一致的类型;分配表明所需的类型是“Vector3?”。考虑将结果和/或替代转换为所需的类型。”我>

标签: c# xna


【解决方案1】:

您的第一个参数是 Vector3 类型(不是 Vector3?)。由于 null 不是 Vector3 的有效值,因此您会收到错误消息。

将行改为:

float? distance = ray.Intersects(plane);
return distance.HasValue ? (Vector3?)(ray.Position + ray.Direction * distance.Value): null;

您需要将三元的左侧显式转换为 Vector3?让它工作。第二个代码 sn-p 有效,因为 Vector3 可以隐式转换为 Vector3?。在三元组中,这种转换不会发生,因此您必须明确地进行。

【讨论】:

  • 但是我在第二个 sn-p 中的 return 语句不也是 Vector3,因此也应该抛出同样的错误吗?
  • 为我的回答添加了解释。如果您仍然感到困惑,请告诉我!
  • 很好的解释。谢谢!
猜你喜欢
  • 2021-02-06
  • 2021-09-02
  • 2019-08-09
  • 2020-02-27
  • 2021-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-27
相关资源
最近更新 更多