1

我以不再使用 VisualBasic 命名空间的方式重写了我的函数。
例如像这样:

Public Function _Between(ByVal _string As String, _
                         ByVal _firstchar As String, _
                         ByVal _secondchar As String) As String

    Dim retval As String = ""
    Dim first, second As Integer

    Try
        first = _string.IndexOf(_firstchar) + 1
        second = _string.IndexOf(_secondchar) - 1
        If first >= 0 And second >= 0 Then
            retval = _string.Substring(first, second)
        End If
    Catch ex As Exception
    End Try
    Return retval
End Function

这是从给定字符“first”和“second”之间的现有字符串创建字符串的函数,类似于 Basic MID$ 函数。

这个函数的使用是经典的,例如:

mynumber = CDbl(_Between(cbovalue, " ", "%"))

问题是:
这里是否可能(以及如何)对原始.NET的“字符串”类进行子类化,以便我可以在更多“NET”方式上使用这样的函数,如下所示:

 mynumber = CDbl(cbovalue._Between(" ", "%"))

...并在 VB.IDE 的建议列表中获取成员“_Between”?

4

1 回答 1

2

该功能称为扩展方法:扩展方法(Visual Basic)

Imports System.Runtime.CompilerServices

Public Module StringExtensions

    <Extension>
    Public Function _Between(ByVal _string As String, _
                         ByVal _firstchar As String, _
                         ByVal _secondchar As String) As String

        Dim retval As String = ""
        Dim first, second As Integer

        Try
            first = _string.IndexOf(_firstchar) + 1
            second = _string.IndexOf(_secondchar) - 1
            If first >= 0 And second >= 0 Then
                retval = _string.Substring(first, second)
            End If
        Catch ex As Exception
        End Try
        Return retval
    End Function

End Module

有了它,您将能够按照您的描述调用该方法:从第一个参数类型开始,仅指定其余参数:

cbovalue._Between(" ", "%")

当然,cbovalue必须是String可变的。

于 2013-10-12T15:30:27.297 回答