2012-02-28 73 views
-1

我正在编写一个类库,我希望能够使用New关键字的用户(将使用此库的用户)。在用户的部分上的编码看起来是这样的:VB.NET类实例

Dim result As Integer = MyLibrary.MyObject.Sum(1,2) 

这是一个简化的例子,但你明白了。难题在于MyObject需要实例化,因为它拥有自己的私有属性来跟踪。

这就像为用户创建MyLibrary的上下文。这是可行的吗?

+4

'New'关键字有什么问题? – SLaks 2012-02-28 04:37:11

+0

你正在寻找一个单身人士。现在你知道它叫什么了,你可以用Google来做它。可能会出现一些已经提出并回答的SO问题。 – 2012-02-28 08:06:21

回答

0

可以使用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