接口和oop概念的新手

时间:2016-07-13 03:19:25

标签: vb.net oop interface

我理解oop中接口的概念,但实现它对我来说很有挑战性。这些是我的课程:

qDebug

目前,我在Class Parent中有以下两个函数

Public Class Alpha 
   Public Property Id As Integer
   Public Property StartDate as Date
   Public Property System as string
   Public Sub Deserialize(ByVal row As DataRow)
       Me.Id = row("Id ") ...
   end sub
end class

Public Class Bravo
   Public Property Id As Integer
   Public Property StartDate as Date
   Public Property Dosage as integer
   Public Sub Deserialize(ByVal row As DataRow)
       Me.Id = row("Id ") ...
   end sub
end class

Public Class Parent
   Public Property Id As Integer
   Public Property Name as String
   Public Property AdmitDate as Date  
   Public Sub Deserialize(ByVal row As DataRow)
       Me.Id = row("Id ") ...
   end sub     
end class

Public Class AlphaList inherits List(of Alpha)
    Public Sub Deserialize(table As DataTable)
     For Each objRow As DataRow In table.Rows
        Dim obj As New Bravo            
        obj.Deserialize(objRow)            
        Me.Add(obj)
     Next
    end sub    
end Class

Public Class BravoList inherits List(of Bravo)
    Public Sub Deserialize(table As DataTable)
     For Each objRow As DataRow In table.Rows
        Dim obj As New Bravo            
        obj.Deserialize(objRow)            
        Me.Add(obj)
     Next
    end sub
end Class

Public Class ParentList inherits List(of Parent)
    Public Sub Deserialize(table As DataTable)
     For Each objRow As DataRow In table.Rows
        Dim obj As New Parent
        obj.Deserialize(objRow)            
        Me.Add(obj)
     Next
    end sub
end Class

基本上,它们具有相同的实现,唯一不同的是参数 - AlphaList或BravoList。

我想在Class Parent中创建一个带有任何AlhpaList或BravoList的函数。我该怎么做?提前致谢!! ..我想将它们全部一起提取出来并做一些像(伪代码)那样的事情:

public Sub RunA(aList as AlphaList )
    For each item as Alpha in alist
       item.Id ....
    next
end sub
public Sub RunB(bList as BravoList )
    For each item as Bravo in bList 
       item.Id ....
    next
end sub

1 个答案:

答案 0 :(得分:1)

你真正要求的是不可能的。 AlphaBravo是不同的类型,因此其StartDate属性是不同的属性。它们具有相同名称的事实并没有改变它。你可以使用后期绑定,但这将是一个肮脏的黑客。

即使您定义了具有StartDate属性的界面并且AlphaBravo实现了该属性,它仍然不允许您传递List(Of Alpha)或者List(Of Bravo)到期望List(Of ISomeInterface)的参数。

如果您有这样的界面,您至少可以编写一个具有该类型参数的方法,然后在List(Of Alpha)List(Of Bravo)方法的循环中调用它参数。