编写不需要初始化的固定功能

时间:2018-09-14 10:25:37

标签: vb.net

我编写了一个函数来从“ xx”:“ ...”格式中提取接收到的令牌

Public Class HelperFunctions
    Public Function ExtractToken(ByVal myToken As String) As String
        'Split fields on comma
        Dim fields = myToken.Split(":")
        'Quote literal
        Dim quote = """"c
        'Use trim to remove quotes
        Dim value = fields(2).Trim(quote)
        Return value
    End Function
End Class

但是不要初始化函数

Dim hc as New HelperFunctions
hc.ExtractToken(_string)

我想直接使用它

HelperFunctions.ExtractToken(_string)

我已经有一段时间没有编程了,无法弄清楚,也没有想出这种函数的名称来查找教程。

1 个答案:

答案 0 :(得分:4)

您需要将函数声明为Shared

Public Class HelperFunctions
    Public Shared Function ExtractToken(ByVal myToken As String) As String
        'Split fields on comma
        Dim fields = myToken.Split(":")
        'Quote literal
        Dim quote = """"c
        'Use trim to remove quotes
        Dim value = fields(2).Trim(quote)
        Return value
    End Function
End Class

或者如@jmcilhinney所述,您可以使用Module,而不必在其内部的方法中使用Shared(也不能从Module创建对象的实例):

Public Module HelperFunctions
    Public Function ExtractToken(ByVal myToken As String) As String
        'Split fields on comma
        Dim fields = myToken.Split(":")
        'Quote literal
        Dim quote = """"c
        'Use trim to remove quotes
        Dim value = fields(2).Trim(quote)
        Return value
    End Function
End Module