Startsidan  ▸  Texter  ▸  Teknikblogg

Anders Hesselbom

Programmerare, skeptiker, sekulärhumanist, antirasist.
Författare till bok om C64 och senbliven lantis.
Röstar pirat.

Automatic object duplication

2010-02-13

While working on my new Monkeybone control, I was on my way to create an abstract base class that declared a function called Copy for duplicating a drawing instruction. My plan was that each instruction (such as a Line or a Bar) had to provide an implementation of the Copy method, so that each instruction could be duplicated and modified as needed. A quick Google search made me change strategy. I found this function for C# by James Crowley that I quickly rewrote for VB:

Public Function Copy() As Instruction
    Using memStream As New System.IO.MemoryStream()
        Dim C As New System.Runtime.Serialization.StreamingContext( _
            System.Runtime.Serialization.StreamingContextStates.Clone)
        Dim Bf _
           As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(Nothing, C)
        Bf.Serialize(memStream, Me)
        memStream.Seek(0, IO.SeekOrigin.Begin)
        Return CType(Bf.Deserialize(memStream), Instruction)
    End Using
End Function

With this function completely implemented in the in the abstract base class, any serializable object that inherits from the base class, has a function called Copy that creates a new instance if the object and initializes it in the same way as the object that the Copy function is called on. Really cool. Now check this: The Line class inherits from my abstract base class. The base does not contain any data (the line coordinates are stored in the Line class), but the Line class does not contain any hints on how copying is done. But still:

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles MyBase.Load
    Dim L1 As New Monkeybox.Line(10, 20, 30, 40)
    Dim L2 As Monkeybox.Line = CType(L1.Copy(), Monkeybox.Line)
    L1.X1 += 1
    MessageBox.Show(L2.X1.ToString())
End Sub

Yep! L1.X1 is 11 but L2.X1 is still 10. Woow!

Categories: Visual Basic 9

Leave a Reply

Your email address will not be published. Required fields are marked *



En kopp kaffe!

Bjud mig på en kopp kaffe (20:-) som tack för bra innehåll!

Bjud på en kopp kaffe!

Om...

Kontaktuppgifter, med mera, finns här.

Följ mig

Twitter Instagram
GitHub RSS

Public Service

Folkbildning om public service.

Hem   |   linktr.ee/hesselbom   |   winsoft.se   |   80tal.se   |   Filmtips