我会使用组合类型,我会告诉你原因:因为值的计算应该返回值,而不是改变一堆变量。一旦您需要多个变量突变,则突变一堆变量就无法扩展。假设你想要一千个这样的东西:
IEnumerable<Ray> rays = GetAThousandRays();
var intersections = from ray in rays
where Intersect(ray, out distance, out normal)
orderby distance ...
执行查询现在重复地改变相同的两个变量。您正在根据正在变异的值进行排序。这是一团糟。不要做出改变事物的查询;这很令人困惑。
你想要的是:
var intersections = from ray in rays
let intersection = Intersect(ray)
where intersection.Intersects
orderby intersection.Distance ...
无突变;将一系列值作为值而不是变量来操作。
我也倾向于摆脱那个布尔标志,并使值成为不可变的结构:
// returns null if there is no intersection
Intersection? Intersect(Ray ray) { ... }
struct Intersection
{
public double Distance { get; private set; }
public Vector3 Normal { get; private set; }
public Intersection(double distance, Vector3 normal) : this()
{
this.Normal = normal;
this.Distance = distance;
}
}