这个问题的背景是我正在编写一个光线追踪器。
我有一个 "Surface" 类型,理想情况下我希望它是一个抽象基类,由 "NoSurface" 和 "Lambertian" 继承而来。
然而,当我拥有这个继承关系时,我遇到了以下问题:
我有一个 "Surface" 类型,理想情况下我希望它是一个抽象基类,由 "NoSurface" 和 "Lambertian" 继承而来。
然而,当我拥有这个继承关系时,我遇到了以下问题:
let closestIntersection : bool*LineParameter*Surface =
match allIntersectionsWithRealSolutions with
| [] -> (false,0.0f, NoSurface(0UL,NotHitable(),Material(Vector3.Zero)))
| x::xs -> List.reduce (fun smallest current -> smallestIntersection smallest current) allIntersectionsWithRealSolutions
由于它将返回类型绑定到NoSurface,即使将类型指定为Surface,因此会引发编译器错误。
以下更正了此问题:
let closestIntersection : bool*LineParameter*Surface =
match allIntersectionsWithRealSolutions with
| [] -> (false,0.0f, NoSurface(0UL,NotHitable(),Material(Vector3.Zero)) :> Surface)
| x::xs -> List.reduce (fun smallest current -> smallestIntersection smallest current) allIntersectionsWithRealSolutions
closestIntersection
但是根据BenchmarkDotNet的测试结果,使用强制类型转换:>
比将Surface定义为一个非抽象类并直接返回它的解决方案多花费了25ms的时间!
我能否以某种方式避免显式强制类型转换并获得所需的Surface抽象类层次结构?
| [] -> (false,0.0f, (upcast NoSurface(0UL,NotHitable(),Material(Vector3.Zero)) : Surface))
,你是对的!它更快了很多!大约25ms。谢谢!为什么会有这样的性能差异呢? - Marc HPunkt