不,你想要在你的情況下做什麼有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
我基本上這樣做,除了它不是一個共享函數(無論哪種方式無關)。如果可能的話,我只想避免f =部分。 – John
@John:不幸的是,你不能將對象設置爲自己的新版本,並且在某些時候你必須將屬性賦值給某些東西,所以需要'f ='。我已經用基於泛型的實現更新了答案,這可能對您更好。 –