我正在开展一个项目,发现自己缺乏OOP知识:
我想使用包含所有派生类的公共代码的基类方法。问题是它需要处理的属性在每个派生类中都是不同的类型,因此它不会在基类中“看到”它们。例如:
Public Interface IBase
Function CommonMethod() As Integer
End Interface
Public MustInherit Class BaseProperties
Public Property prop1 As String
Public Property prop2 As String
End Class
Public Class ActualProperties1 : Inherits BaseProperties
Public Property prop3 As String
Public Property prop4 As String
End Class
Public MustInherit Class BaseClass : Implements IBase
'placeholder for the actual PropertyClass class defined in each derived class
Public Overridable Property PropertyClass As Object
Public Function CommonMethod() As Integer Implements IBase.CommonMethod
Dim Varis as String = ""
'This correctly shows the derived class name
MsgBox(Me.GetType.Name)
'This throws an exception, as it is referencing the base class object which is nothing
MsgBox(Me.PropertyClass.GetType.Name)
'This is closer to what I actually want to do.
For Each prop As ComponentModel.PropertyDescriptor In ComponenModel.TypeDescriptor.GetProperties(Me.PropertyClass)
If prop.PropertyType.ToString = "System.String" Then
Varis += prop.GetValue()
prop.SetValue(Me.PropertyClass, "")
End If
Next
'Do something with Varis
End Function
End Class
Public Class DerivedClass : Inherits BaseClass
Public Property PropertyClass As ActualProperties1
Public Sub New()
PropertyClass = New ActualProperties1
End Sub
End Class
Public Class Form1
Dim cli As New DerivedClass
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
cli.prop1 = "test"
cli.prop4 = "test"
cli.CommonMethod()
End Sub
End Class
还有一些其他的类从BaseClass继承,并且有自己的一组属性来扩充BaseProperties,这些属性对于其他类不常见,但CommonMethod()操作对于所有类都是相同的。
基本上我想避免:
我环顾四周,看来这是不可能的,如果没有做另一个课程,但我不确定,因为答案是在C#,所以有可能这是重复。
谢谢你的时间!
答案 0 :(得分:0)
基类不应该知道它的子类。你可以做的是在基类上定义一个公共函数并将其标记为MustOverride
,这将迫使子类实现它。每个子类实现都知道它自己的结构,并可以根据需要计算派生属性。您可以对“属性”,“函数”和“子”执行此操作。
看到这个例子,我只是在一起:
Module Module1
Sub Main()
Dim Thing1 As BaseClass = New DerivedClass1 With {.NumberOfCows = 10}
Dim Thing2 As BaseClass = New DerivedClass2 With {.NumberOfGoats = 5, .NumberOfChickens = 20}
Console.WriteLine(Thing1.CalculateNumberOfAnimals()) 'Prints 10
Console.WriteLine(Thing2.CalculateNumberOfAnimals()) 'Prints 25
End Sub
Public MustInherit Class BaseClass
Public MustOverride Function CalculateNumberOfAnimals() As Integer
End Class
Public Class DerivedClass1
Inherits BaseClass
Public Property NumberOfCows As Integer
Public Overrides Function CalculateNumberOfAnimals() As Integer
Return NumberOfCows
End Function
End Class
Public Class DerivedClass2
Inherits BaseClass
Public Property NumberOfChickens As Integer
Public Property NumberOfGoats As Integer
Public Overrides Function CalculateNumberOfAnimals() As Integer
Return NumberOfChickens + NumberOfGoats
End Function
End Class
End Module