C# 三元运算符不能正确使用Vector3

C# 三元运算符不能正确使用Vector3,c#,xna,C#,Xna,我这里有两个代码片段,第一个产生错误,但第二个工作。为什么? public static Vector3? GetRayPlaneIntersectionPoint(Ray ray, Plane plane) { float? distance = ray.Intersects(plane); return distance.HasValue ? ray.Position + ray.Direction * distance.Value : null; } Give:无法确定条

我这里有两个代码片段,第一个产生错误,但第二个工作。为什么?

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”之间没有隐式转换

但是下面没有三元运算符的代码片段工作得很好

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;
}

您的第一个参数是Vector3类型(不是Vector3?)。由于null不是矢量3的有效值,因此会出现错误

将行更改为:

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

您需要显式地将三元的左侧强制转换为Vector3?让它工作。第二个代码段之所以有效,是因为
Vector3
可以隐式转换为
Vector3?
。在三元代码中,此转换不会发生,因此必须显式执行。

但是,我的第二个代码段中的返回语句不是也是Vector3,因此也应该抛出相同的错误吗?在我的答案中添加了解释。如果你仍然困惑,请告诉我!很好的解释。非常感谢。这个问题的可能重复在这个网站上被问了数百次。C语言要求表达式从内到外求值。表达式外部存在到可空类型的转换这一事实并不影响表达式内部的分析方式;相反,情况恰恰相反。一旦确定了表达式内部的类型,就会将其与外部的类型进行比较,以确定其是否兼容。我想这是一个很大的误解,即条件表达式的工作原理应该相同,而三元运算符更像是语法糖。你的观点是正确的。数百人,或者更可能是数千人对此感到困惑,这表明运营商的设计可能存在缺陷。或者,从另一个角度考虑:该规则是合理的,但错误信息可能会更清楚。它可以说“条件运算符的结果和替换必须具有一致的类型;赋值表明所需的类型是“向量3”。考虑将结果和/或替换为所需类型。”