The first option is fair enough when there is a certain work, which, as you know, will be different for derived classes. Perhaps you want to have
Public MustInherit Class T Protected MustInherit Function Clone() As T Public Function CloneAdjusted() As T Dim clone = Me.DoClone() ' Adjust clone ' End Function End Class Public Class A Inherits T Protected Overrides Function Clone() As T ' Make exact copy of A ' End Function End Class
The second approach would be more appropriate if you just want to clone any old T, but want to make minor adjustments to subclasses. But in this case, override the Clone method, and do not create a new one with a new name. for instance
Public MustInherit Class T Public Overridable Function Clone() As T Dim clone = ' Clone a T here ' End Function End Class Public Class A Inherits T Public Overrides Function Clone() As T ' Any pre-clone work ' T obj = MyBase.Clone() ' Any post-clone work ' End Function End Class
And no, that doesn't make much sense for the clone when you look at it, because you are going to get T back from the base clone, and converting this to is not that easy.
There are several other options that you might consider.
One of them is a helper class. Instead of having any code in T, you may need to move your generic code to a static method of a static class to avoid duplication.
The other has an ICloner interface, which T understands the contract, but A and B understand the implementation, for example
Public MustInherit Class T Protected ICloner Cloner Public Overridable Function Clone() As T ' Common Code ' Dim clone = Cloner.GetClone() ' More Common Code ' End Function End Class Public Class A Inherits T Public Sub New() Cloner = New ACloner(Me) End Sub End Class
Confused enough?
source share