2011-12-06 220 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 ='。我已經用基於泛型的實現更新了答案,這可能對您更好。 –