我在3层项目中有两个库 - 称它们为BO和DAL。几乎DAL中的每个类都实现了一个保存方法:
Public Function Save(ByVal someObject As BO.SomeType) As Boolean
由于我必须添加缺少的Save方法,我想创建一个实现'MustInherit Save'功能的接口是个好主意。所以,如果我输入:
MustOverride Function Save(ByVal someObject As BO.SomeType) As Boolean
应该这样做;但参数的类型总是不同的。例如,在类DAL.TypeA:
中Public Function Save(ByVal someObject As BO.SomeTypeA) As Boolean
在课堂DAL.TypeB:
Public Function Save(ByVal someObject As BO.SomeTypeB) As Boolean
有没有办法在界面中处理不同类型的参数?某种通用?这甚至可能吗?
答案 0 :(得分:5)
generics的完美用例。
使用通用接口:
<强>接口强>
Interface ISave(Of T)
Function Save(someObject As T) As Boolean
End Interface
<强>实施强>
Class BoClass
Implements ISave(Of BoClass)
Public Function Save(someObject As BoClass) As Boolean Implements ISave(Of BoClass).Save
End Function
End Class
Class DalClass
Implements ISave(Of DalClass)
Public Function Save(someObject As DalClass) As Boolean Implements ISave(Of DalClass).Save
End Function
End Class
或者,使用通用基类而不是接口
基础课程
MustInherit Class BaseClass(Of T)
MustOverride Function Save(someObject As T) As Boolean
End Class
<强>实施强>
Class BoClass
Inherits BaseClass(Of BoClass)
Public Overrides Function Save(someObject As BoClass) As Boolean
End Function
End Class
Class DalClass
Inherits BaseClass(Of DalClass)
Public Overrides Function Save(someObject As DalClass) As Boolean
End Function
End Class
答案 1 :(得分:1)
这看起来像一个实现细节,在这种情况下,您保存的对象应该实现DAL类将调用的接口。
Public Interface ISaveable
Function Save() As Boolean
End Interface
然后执行实际保存的对象实现它:
Public Class BOItem
Implements ISaveable
Public Function Save() As Boolean Implements ISaveable.Save
'do the actual saving here
End Function
End Class
然后您的基类会询问界面:
Public MustInherit Class DAL
MustOverride Function Save(someObject As ISaveable) As Boolean
End Class
然后当你创建DAL对象时,你不必担心它是什么类型的对象,你只需要调用save:
Public Class DALItem
Inherits DAL
Public Overrides Function Save(someObject As ISaveable) As Boolean
Return someObject.Save()
End Function
End Class