-1
我正在編寫一個類庫,我希望能夠使用New關鍵字的用戶(將使用此庫的用戶)。在用戶的部分上的編碼看起來是這樣的:VB.NET類實例
Dim result As Integer = MyLibrary.MyObject.Sum(1,2)
這是一個簡化的例子,但你明白了。難題在於MyObject需要實例化,因爲它擁有自己的私有屬性來跟蹤。
這就像爲用戶創建MyLibrary的上下文。這是可行的嗎?
我正在編寫一個類庫,我希望能夠使用New關鍵字的用戶(將使用此庫的用戶)。在用戶的部分上的編碼看起來是這樣的:VB.NET類實例
Dim result As Integer = MyLibrary.MyObject.Sum(1,2)
這是一個簡化的例子,但你明白了。難題在於MyObject需要實例化,因爲它擁有自己的私有屬性來跟蹤。
這就像爲用戶創建MyLibrary的上下文。這是可行的嗎?
可以使用Singleton模式:
Public Class MyLibrary
Private _MyObject As MyLibrary
Public ReadOnly Property MyObject As MyLibrary
Get
If _MyObject Is Nothing Then
_MyObject = New MyLibrary()
End If
Return _MyObject
End Get
End Property
Public Function Sum(ByVal a As Integer, ByVal b As Integer) As Integer
Return a + b
End Function
End Class
或者你用關鍵字Shared
(在C#這是static
):
Namespace MyLibrary
Public Class MyObject
Public Shared Function Sum(ByVal a As Integer, ByVal b As Integer) As Integer
Return a + b
End Function
End Class
End Namespace
或者,VB.NET,你可以使用一個Module
而不是一個類:
Namespace MyLibrary
Public Module MyObject
Public Function Sum(ByVal a As Integer, ByVal b As Integer) As Integer
Return a + b
End Function
End Module
End Namespace
'New'關鍵字有什麼問題? – SLaks 2012-02-28 04:37:11
你正在尋找一個單身人士。現在你知道它叫什麼了,你可以用Google來做它。可能會出現一些已經提出並回答的SO問題。 – 2012-02-28 08:06:21