tags:

views:

25

answers:

2

D is a dictionary whose entry values are of Type T

What I'm attempting to do is have a delegate like "Serializer" below that I can invoke on an instance of T, such as "Entry.Value" below.

Please see the "return Entry..." line below for my wishful thinking.

Is this possible?

If so, is it a bad idea?

Public Delegate Function Serializer(Of T)() As Byte()

Function SerializeDictionary_String_Object(Of T)(ByRef D As Dictionary(Of String, T), ByVal ObjSerializer As Serializer(Of T)) As Byte()

  for each Entry in D
    return Entry.Value.ObjSerializer()
    exit for
  next

End Function
+2  A: 

In your Serializer delegate, you're not using T anywhere. You should do something like this:

Public Delegate Function Serializer(Of T)(Byval obj As T) As Byte()

Or better yet, just use the built in Func delegate.

Function SerializeDictionary_String_Object(Of T)(ByRef D As Dictionary(Of String, T), ByVal ObjSerializer As Func(Of T, Byte()) As Byte()

Then call it by doing:

ObjSerializer(Entry.Value)

I'm extremely rusty at VB so my apologies if I missed an underscore or something. :)

Josh Einstein
ObjSerializer in your example is a shared (or static) function. I need it to be an instance function. If I'm forced to use shared functions, then I will have to have a shared and instance version of every serializer function.
hamlin11
I'm not sure what the VB syntax would be but in C# you can use a lambda for this purpose: SerializeDictionary_String_Object(dict, x => x.Serialize()) - the method signatures above would not need to change.
Josh Einstein
+1  A: 

Maybe an extension method like that one ?

Imports System.IO
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.Runtime.CompilerServices

Public Module ModuleTupExtension
    <Extension()> _
    Public Function DeepClone(Of T)(ByVal a As T) As T
        Using stream As New MemoryStream()
            Dim formatter As New BinaryFormatter()
            formatter.Serialize(stream, a)
            stream.Position = 0
            Return DirectCast(formatter.Deserialize(stream), T)
        End Using
    End Function

    <Extension()> _
    Public Function toSerializedByteArray(Of T)(ByVal a As T) As Byte()
        Using stream As New MemoryStream()
            Dim formatter As New BinaryFormatter()
            formatter.Serialize(stream, a)
            stream.Position = 0
            Return stream.ToArray()
        End Using
    End Function
End Module

I left the deepclone since I did it from that one. Will only work on objects marked as < Serializable > though.

Also, I haven't tried it on really big objects or recursives ones.

Cheers !

Alex Rouillard