调用一个方法,需要一个派生类实例类型作为基类在VB.NET或C#
我有两个对象 - 太空船和星球派生自基地Obj。我已经定义了几个类 - Circle,Triangle,Rectangle等,它们都继承自一个Shape类。
I have two objects - "Spaceship" and "Planet" derived from a base "Obj". I have defined several classes - Circle, Triangle, Rectangle, etc. which all inherit from a "Shape" Class.
为了碰撞检测的目的,我想给Obj a shape:
For collision detection purposes, I want to give Obj a "shape":
Dim MyShape as Shape
在宇宙飞船中,我可以:
So that in "Spaceship" I can:
MyShape = new Triangle(blah,blah)
,在Planet中可以:
and in "Planet" I can:
MyShape = new Circle(blah,blah)
我有一个方法(重载几次),它检查不同形状之间的冲突,例如:
I have a method (overloaded several times) which checks for collisions between different shapes, for example:
public shared overloads function intersects(byval circle1 as circle, byval circle2 as circle) as boolean
AND
public shared overloads function intersects(byval circle as circle, byval Tri as triangle) as boolean
当我使用派生类调用函数时,这样工作很好,例如:
This works fine when I call the function using the derived classes, for example:
dim A as new circle(blah, blah)
dim B as new triangle(blah, blah)
return intersects(A,B)
但是当我使用MyShape调用它时,我得到一个错误,因为该方法正在传递一个Shape(而不是派生类型)方法不会有重载。
But when I call it using MyShape, I get an error because the method is being passed a "Shape" (rather than the derived type) which the method does not have an overload for.
我可以通过执行以下操作来解决:
I could solve it by doing something like:
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
但这看起来很乱。有更好的方法吗?
But that seems messy. Is there a better way?
一个办法是插入 MyActualFunction
作为类成员。
A way around it is to insert MyActualFunction
as a class member.
在形状:
Public MustOverride Function MyActualFunction()
End Function
在圆和三角形中:
Public Overrides Function MyActualFunction()
End Function
然后调用它:
MyShape.MyActualFunction()
,这将知道要调用的函数。
and this will know which function to call.