2011-12-06 175 views
0

这可能吗?反序列化对象内的对象

Public Class Foo 
    public var as string 

    public sub Load(byval filename as string) 
     'This is done 
     [...] 
     oItem = [...] 'Code to deserialize 

     me = oItem 'THIS LINE 
    end sub 
end class 

这样就可以从序列文件加载富像这样:

Public Sub Main 
    Dim f as Foo = new Foo() 
    f.load("myFile") 
end sub 

直至现在我已经有这样的返回美孚作为对象的函数(我试图使序列化/反序列化过程一般,所以我可以复制和粘贴,并避免明确设置每个变量)

回答

1

不,你想要在你的情况下做什么有Load是一个共享函数,返回新创建的项目。

更多类似:

Public Class Foo 
    public var as string 

    public Shared Function Load(byval filename as string) As Foo 
     'This is done 
     [...] 
     oItem = [...] 'Code to deserialize 

     Return oItem 
    end sub 
end class 

Public Sub Main 
    Dim f as Foo 
    f = Foo.load("myFile") 
end sub 

另外,而不是直接嵌入反序列化到每个类别中,可以有一个通用的方法,如:

''' <summary> 
''' This method is used to deserialize an object from a file that was serialized using the SoapFormatter 
''' </summary> 
''' <param name="sFileName"></param> 
''' <returns></returns> 
''' <remarks></remarks> 
Public Function Deserialize(Of T)(ByVal sFileName As String) As T 
    ' Exceptions are handled by the caller 

    Using oStream As Stream = File.Open(sFileName, FileMode.Open, IO.FileAccess.Read) 
     If oStream IsNot Nothing Then 
      Return DirectCast((New SoapFormatter).Deserialize(oStream), T) 
     End If 
    End Using 

    Return Nothing 
End Function 

然后可以调用如:

Public Sub Main 
    Dim f as Foo 
    f = Deserialize(Of Foo)("myFile") 
end sub 
+0

我基本上这样做,除了它不是一个共享函数(无论哪种方式无关)。如果可能的话,我只想避免f =部分。 – John

+0

@John:不幸的是,你不能将对象设置为自己的新版本,并且在某些时候你必须将属性赋值给某些东西,所以需要'f ='。我已经用基于泛型的实现更新了答案,这可能对您更好。 –