0

我有两个对象——从基础“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

但这似乎很混乱。有没有更好的办法?

4

2 回答 2

1

一种解决方法是MyActualFunction作为类成员插入。

形状:

Public MustOverride Function MyActualFunction()
End Function

在圆形和三角形中:

Public Overrides Function MyActualFunction()
End Function

然后这样称呼它:

MyShape.MyActualFunction()

这将知道要调用哪个函数。

于 2012-10-23T06:37:47.633 回答
0

Polymorphism can't help you with that therefore you'll have to create a common method with both parameters of type Shape and then distinguish them inside it:

Public Function DoCollide(ByRef shape1 As Shape, ByRef shape2 As Shape) As Boolean
    If TryCast(shape1, Circle) IsNot Nothing And TryCast(shape2, Circle) IsNot Nothing Then
        Return DoCollide(TryCast(shape1, Circle), TryCast(shape2, Circle))
    ElseIf TryCast(shape1, Circle) IsNot Nothing And TryCast(shape2, Triangle) IsNot Nothing Then
        Return DoCollide(TryCast(shape1, Circle), TryCast(shape2, Triangle))
    Else
        Return False
    End If
End Function

I would put this function along with all the specialized implementations doing the actual collision detection in their own class CollisionDetector

Public Class CollisionDetector

    Public Function DoCollide(ByRef shape1 As Shape, ByRef shape2 As Shape) As Boolean
        If TryCast(shape1, Circle) IsNot Nothing And TryCast(shape2, Circle) IsNot Nothing Then
            Return DoCollide(TryCast(shape1, Circle), TryCast(shape2, Circle))
        ElseIf TryCast(shape1, Circle) IsNot Nothing And TryCast(shape2, Triangle) IsNot Nothing Then
            Return DoCollide(TryCast(shape1, Circle), TryCast(shape2, Triangle))
        Else
            Return False
        End If
    End Function

    Public Function DoCollide(ByRef circle1 As Circle, ByRef circle2 As Circle) As Boolean
        Return True
    End Function

    Public Function DoCollide(ByRef circle As Circle, ByRef triangle As Triangle) As Boolean
        Return True
    End Function

End Class
于 2012-10-23T17:54:02.577 回答