c# - out 用于多个输出值或返回组合值类型更好吗?

标签 c# .net performance clarity

例如,按照以下行:

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/

相关文章:

javascript - 将复杂对象传递给 javascript 函数与单个 var 的性能差异?

C# 方法慢 100 倍,三个返回比两个?

c# - Mahapps 的全屏行为

c# - 在 Xamarin.Android 中向通知添加声音

c# - 如何避免序列化 float 组属性

c# - 跳过 Facebook 登录窗口

.net - 线程开销

c# - Azure Functions V1 DI 的依赖项注入(inject)

javascript - 在 JS 中查询 boolean 变量与比较两个字符串

c# - 获取当前用户的 NetworkCredential (C#)