VB.NET类实例

时间:2012-02-28 04:31:59

标签: vb.net class

我正在编写一个类库,我希望我可以使用New关键字来节省用户(将使用此库的人)。用户的编码看起来像这样:

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

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

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

1 个答案:

答案 0 :(得分:0)

您可以使用单例模式:

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