开发者

VB.NET - How do I invoke an instance function delegate on an instance of a generic type?

开发者 https://www.devze.com 2023-01-10 07:23 出处:网络
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.

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


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. :)


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 !

0

精彩评论

暂无评论...
验证码 换一张
取 消