我有一个名为dRow的类,其中包含一些数据。我有dRow,AccountRow,PageRow等许多子类。它们仅在代码上有所不同。现在,我想向dRow添加一个单例...
Protected Shared EmptyRow as dRow
EmptyRow是dRow的实例,不包含任何数据。在下面是这个...
Public Function EmptyRow() as dRow...
现在的问题...我需要AccountRow来将EmptyRow作为AccountRow(而不是dRow)返回...
Friend Function EmptyRow() as AccountRow...
DirectCast无法正常工作,这是错误的方向。它看起来像我不得不为每个子类单独EmptyRow?
有什么办法可以避免这种命运?
泛型可能会起作用。您是在创建实例dRow
还是仅将其用作基类?如果只是基类(可以有MustInherit
关键字),请尝试如下操作:
MustInherit Class dRow(Of T As New)
Protected Shared _emptyRow As New T
Public Shared Function EmptyRow() As T
Return _emptyRow
End Function
End Class
Class AccountRow
Inherits dRow(Of AccountRow)
End Class
Class PageRow
Inherits dRow(Of PageRow)
End Class
该EmptyRow
函数现在将返回子类类型的单例实例。
您甚至可以像这样添加进一步的泛型类型约束,以确保子类仅使用的实例dRow
作为其类型。
MustInherit Class dRow(Of T As {dRow(Of T), New})
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句