假设我有这样的数据库结构:
create table Product(id int not null identity,Name varchar(30))
INSERT INTO Product VALUES ('ProductA')
INSERT INTO Product VALUES ('ProductB')
和这样的类结构:
Imports System.Data.SqlClient
Public Class Product
Protected ProductName As String
Public Overridable Sub Display()
End Sub
End Class
Public Class ProductA
Inherits Product
Public Sub New(ByVal product As String)
ProductName = product
End Sub
Public Overrides Sub Display()
'Specific logic to display product A
End Sub
End Class
Public Class ProductB
Inherits Product
Public Sub New(ByVal product As String)
ProductName = product
End Sub
Public Overrides Sub Display()
'Specific logic to display product B
End Sub
End Class
Public Class Form1
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim p1 As Product
Dim p2 As Product
p1 = New ProductA("ProductA")
p2 = New ProductB("ProductB")
p1.Display()
p2.Display()
End Sub
End Class
有一个属性(产品)可以识别该类与哪个产品相关。这对我来说看起来不正确。有没有更好的建模方法?这类似于鉴别器的NHibernate概念(在这种情况下我没有使用NHibernate)。
答案 0 :(得分:0)
随着最新的更改,您应该将构造函数移动到基类。除此之外,设计还不错。
Public Class Product
Protected ProductName As String
Public Sub New(ByVal product As String)
ProductName = product
End Sub
Public Overridable Sub Display()
End Sub
End Class
Public Class ProductA
Inherits Product
Public Overrides Sub Display()
'Specific logic to display product A
End Sub
End Class
此外,在您的声明中,您可以使用继承的类:
Dim p1 As ProductA
Dim p2 As ProductB