给出这个例子:
Imports System
Public Module Module1
Public Sub Main()
Console.WriteLine("Expect 'WheelValue' here.")
Dim car as New Car()
car.DoSomething()
Console.WriteLine("Expect 'FordWheelValue' here.")
Dim ford as New Ford()
ford.DoSomething()
End Sub
Public Class Car
Public Sub DoSomething()
Console.WriteLine("Car.DoSomething()")
Console.WriteLine("Wheel=" + Wheel.Value)
Console.WriteLine(Environment.NewLine)
End Sub
Public Property Wheel As New Wheel()
End Class
Public Class Ford
Inherits Car
Public Shadows Property Wheel As New FordWheel()
End Class
Public Class Wheel
Public Value As String = "WheelValue"
End Class
Public Class FordWheel
Public Value As String = "FordWheelValue"
End Class
End Module
致电Ford.DoSomething()
使用基类的属性Wheel.Value
。为了不复制代码,有没有办法使用VB干净地编写它,以便这些调用Ford.DoSomething()
而不是获取福特的属性FordWheel.Value
的实例?
看起来我可能需要的是像#34; Shadows Overrides" - 但从我所知道的,VB中并不支持这一点。
答案 0 :(得分:0)
您希望使基类属性可覆盖:
Public Class Car
Public Sub DoSomething()
Console.WriteLine("Car.DoSomething()")
Console.WriteLine("Wheel=" + Wheel.Value)
Console.WriteLine(Environment.NewLine)
End Sub
Public Overridable Property Wheel As New Wheel()
End Class
然后,当您声明派生类时,将您的属性标记为"接管"现有的:
Public Class Ford
Inherits Car
Public Overrides Property Wheel As Wheel = New FordWheel()
End Class
注意:要实现此目的,您需要将FordWheel
类型更改为从Wheel
类型继承。您还需要设置fordwheel的值,而不是创建一个" shadowed"如果你只是直接继承会发生什么:
Public Class FordWheel
Inherits Wheel
Public Sub New()
Value = "FordWheel"
End Sub
End Class
正如Saragis所说,您应该直接在Wheel
的构造函数中将New FordWheel
属性设置为Ford
,就像我上面使用FordWheel
答案 1 :(得分:0)
您可以重新定义您在Ford类中使用的Wheel类型。由于签名是相同的,因此不再需要在福特定义车轮。 FordWheel现在是Wheel的后代并且超越了Value属性。
Public Class Car
Public Sub New()
Wheel = New Wheel()
End Sub
Public Sub DoSomething()
Console.WriteLine("Car.DoSomething()")
Console.WriteLine("Wheel=" + Wheel.Value)
Console.WriteLine(Environment.NewLine)
End Sub
Public Property Wheel As Wheel
End Class
Public Class Ford
Inherits Car
Public Sub New()
Wheel = New FordWheel()
End Sub
End Class
Public Class Wheel
Public Overridable Property Value As String = "WheelValue"
End Class
Public Class FordWheel
Inherits Wheel
Public Overrides Property Value As String = "FordWheelValue"
End Class
答案 2 :(得分:0)
正如两位已经回答过的人所指出的那样,你需要使用泛化概念,因为FordWheel
是Wheel
。
以下代码只是一种名为Bridge Pattern的流行设计模式的相似之处,其中实现和结构被分离出来。
Public Class Car
Public Sub New()
Wheel = New Wheel()
End Sub
Public Property Wheel As Wheel
End Class
Public Class Ford
Inherits Car
Public Sub New()
Wheel = New FordWheel()
End Sub
End Class
Public Class Wheel
Public Overridable Property Value As String = "WheelValue"
End Class
Public Class FordWheel
Inherits Wheel
Public Overrides Property Value As String = "FordWheelValue"
End Class
Public Class Executor
Public Sub Main()
Console.WriteLine("Expect 'WheelValue' here.")
Dim car as New Car()
Console.WriteLine(car.Wheel)
Console.WriteLine("Expect 'FordWheelValue' here.")
Dim ford as New Ford()
Console.WriteLine(ford.Wheel)
End Sub
End Class
对不起,如果有错误的语法,因为我是Java开发人员。