我有一个项目,主要有两个对象,都从一个基础继承.像这样: Public Class Vehicle Property Model As String Property Make As StringEnd ClassPublic Class Truck Inherits Vehicle Property IsFlatbed As BooleanEnd ClassPublic Cl
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
很简单,嗯?因为我不知道用户是选择汽车还是卡车,我想做的只是绕过车辆.
所以,像这样:
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
上述功能不起作用,因为myVehicle是一辆车,而不是卡车.
有没有办法可以传递一种车辆类型并让IDE知道要使用哪种类型?或者我完全错过了更好的方法吗?
这是您可以实现此目的的一种方式:Imports System.Reflection Module main_ Sub Main() Dim t As New Truck Dim c As New Car Dim v As Vehicle v = t SetFlat(v) v = c SetFlat(v) End Sub Sub SetFlat(ByVal v As Vehicle) Dim vehicletype As Type Dim members() As PropertyInfo vehicletype = v.GetType members = vehicletype.GetProperties Console.Write("v is a " & vehicletype.ToString) For Each m As PropertyInfo In members If m.Name = "IsFlatbed" Then m.SetValue(v, True, Nothing) Console.WriteLine(" and now it's a flatbed") Exit Sub End If Next Console.WriteLine(" so flatbed doesn't apply") End Sub End Module
输出:
v is a Vehicles.Truck and now it's a flatbed v is a Vehicles.Car so flatbed doesn't apply