簡體   English   中英

調用需要在VB.NET或C#中將派生類實例鍵入為基類的方法

[英]Call a method that requires a derived class instance typed as base class in VB.NET or C#

我有兩個對象-從基本“ Obj”派生的“太空飛船”和“行星”。 我定義了幾個類-Circle,Triangle,Rectangle等,它們都從“ Shape”類繼承。

為了檢測沖突,我想給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

但這似乎很混亂。 有沒有更好的辦法?

解決方法是將MyActualFunction插入為類成員。

形狀:

Public MustOverride Function MyActualFunction()
End Function

在圓和三角形中:

Public Overrides Function MyActualFunction()
End Function

然后這樣稱呼它:

MyShape.MyActualFunction()

這將知道要調用哪個函數。

多態性無法幫助您,因此您必須使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM