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