0

ベースの「オブジェクト」から派生した「宇宙船」と「惑星」の 2 つのオブジェクトがあります。Circle、Triangle、Rectangle など、いくつかのクラスを定義しました。これらはすべて「Shape」クラスから継承されます。

衝突検出の目的で、Obj に「形状」を与えたいと思います。

Dim MyShape as Shape

そのため、「宇宙船」では次のことができます。

MyShape = new Triangle(blah,blah)

「Planet」では次のことができます。

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

ポリモーフィズムはそれを助けることができないため、型の両方のパラメーターを持つ共通のメソッドを作成し、Shapeその中でそれらを区別する必要があります。

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

この関数を、独自のクラスで実際の衝突検出を行うすべての特殊な実装と共に配置します。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 に答える