gpt4 book ai didi

vb.net - 使用继承的对象类型时传递基本对象类型

转载 作者:行者123 更新时间:2023-12-03 00:34:57 24 4
gpt4 key购买 nike

我有一个项目,主要有两个对象,都继承自基础。像这样:

Public Class Vehicle
Property Model As String
Property Make As String
End Class

Public Class Truck
Inherits Vehicle
Property IsFlatbed As Boolean
End Class

Public Class Car
Inherits Vehicle
Property LeatherSeats As Boolean
End Class

很简单吧?因为我不知道用户是否会选择汽车或卡车,所以我想做的只是传递 Vehicle

所以,像这样:

Public v As Vehicle
Sub WhichVehicle()
Select Case cmbVehicle.SelectedItem
Case Truck
v = New Truck
Case Car
v = New Car
End Select
SetFlat (v)
End Sub

这一切都有效,但现在我只想传递 v 并使用它的属性。喜欢:

Sub SetFlat (myVehicle As Vehicle)
myVehicle.IsFlatbed = True
End Sub

上述函数不起作用,因为 myVehicleVehicle,而不是 Truck

有没有办法可以传递 Vehicle 类型并让 IDE 知道要使用哪种类型?或者我完全错过了更好的方法来做到这一点?

最佳答案

基本上,当您调用 SetFlat 时,您知道您的车辆有一个名为 IsFlatbed 的属性,对吗?

然后您应该声明一个包含此属性的接口(interface)FlattableTruck 类将实现该接口(interface),而 SetFlat 子类将使用 Flattable 对象作为参数,而不是车辆。

编辑:

这个怎么样:

Public Interface IFlattable
Property IsFlatbed() As Boolean
End Interface

Public Class Truck
Inherits Vehicle
Implements IFlattable

Private _isFlatBed as Boolean
Public Property IsFlatbed() as Boolean Implements IFlattable.IsFlatbed
Get
Return _isFlatbed
End Get
Set(ByVal value as Boolean)
_isFlatbed = value
End Set
End Class


Public v As Vehicle
Sub WhichVehicle()
Select Case cmbVehicle.SelectedItem
Case Truck
v = New Truck
SetFlat (DirectCast(v, IFlattable))
Case Car
v = New Car
End Select
End Sub

Sub SetFlat (myVehicle As Flattable)
myVehicle.IsFlatbed = True
End Sub

关于vb.net - 使用继承的对象类型时传递基本对象类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3893687/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com