【发布时间】:2016-04-29 18:19:06
【问题描述】:
我正在做一个项目,发现自己缺乏 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() 操作都是相同的。
基本上我想避免:
- 代码重复,在每个派生类中编写相同的代码
- 使用实际属性作为参数调用基方法,例如 CommonMethod(PropertyClass) ,除非你们告诉我没有其他方法可以做到这一点......只是感觉不对?
我环顾四周,似乎如果不上另一门课,这是不可能的,但我不确定,因为答案是用 C# 编写的,所以这有可能是重复的。
感谢您的宝贵时间!
【问题讨论】:
-
继承不是这样工作的。基类不知道派生类的不同属性。
-
基类将包括所有派生类使用的代码和属性。 但是如果基类方法需要派生类的某些东西,则几乎按照定义,该方法属于另一个类。那个
As Object声明会打扰我。此外,而不是继承 和 接口,看看你是否不能用 MustOveride 以更简单的形式得到同样的东西 -
这看起来像XY Problem。与其问我们你的解决方案有什么问题,不如试着解释一下你的实际问题。
prop.PropertyType.ToString = "System.String"也是一个坏主意,prop.PropertyType Is GetType(System.String)是正确的方法。 -
@KalaNag 如果它使用不同的源属性,那么它们不会做完全相同的事情。看看我下面的回答,每个子类的实现都不同。
-
@KalaNag 我真的不明白这会如何改变任何事情。也许问题是我们对您的问题理解不够。也许你应该回去尝试改写它(或开始另一个问题),以明确你真正想要的结果。我认为您的示例代码显示了您 /think/ 它应该如何工作,这给讨论增加了很多混乱。尝试向我们展示您希望类的用法,而不是展示您认为内部应该是什么样子。
标签: .net vb.net oop inheritance