我有两个对象——从基础“Obj”派生的“宇宙飞船”和“行星”。我已经定义了几个类——圆形、三角形、矩形等,它们都继承自“形状”类。
出于碰撞检测的目的,我想给 Obj 一个“形状”:
Dim MyShape as Shape
所以在“宇宙飞船”中我可以:
MyShape = new Triangle(blah,blah)
在“星球”中,我可以:
MyShape = new Circle(blah,blah)
我有一个方法(重载多次)检查不同形状之间的碰撞,例如:
public shared overloads function intersects(byval circle1 as circle, byval circle2 as circle) as boolean
和
public shared overloads function intersects(byval circle as circle, byval Tri as triangle) as boolean
当我使用派生类调用函数时,这很好用,例如:
dim A as new circle(blah, blah)
dim B as new triangle(blah, blah)
return intersects(A,B)
但是当我使用 MyShape 调用它时,我收到一个错误,因为该方法正在传递一个“Shape”(而不是派生类型),该方法没有重载。
我可以通过执行以下操作来解决它:
Public Function Translate(byval MyShape1 as Shape, byval MyShape2 as Shape )as boolean
if shape1.gettype = gettype(circle) and shape2.gettype=gettype(circle) then ''//do circle-circle detection
if shape1.gettype = gettype(triangle) and shape2.gettype=gettype(circle) then ''//do triangle-circle detection
End Function
但这似乎很混乱。有没有更好的办法?