例如,按照以下行:
public bool Intersect (Ray ray, out float distance, out Vector3 normal)
{
}
对比
public IntersectResult Intersect (Ray ray)
{
}
public class IntersectResult
{
public bool Intersects {get;set;}
public float Distance {get;set;}
public Vector3 Normal {get;set;}
}
哪个在清晰度、易用性和最重要的性能方面更好。
最佳答案
我会使用组合类型,我会告诉你原因:因为值的计算应该返回值,而不是改变一堆变量。一旦您需要改变其中的多个变量,改变一堆变量就不会扩展。假设您想要一千个这样的东西:
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 ...
无突变;操作一系列值作为值而不是作为变量。
我也可能会倾向于摆脱那个 bool 标志,并使值成为一个不可变的结构:
// 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;
}
}
关于c# - out 用于多个输出值或返回组合值类型更好吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5266045/