Microsoft.VisualBasic.Len函數和System.String類中的length屬性的區別

來源:互聯網
上載者:User

環境:vs2003,vs.net
一般我求一個字串的長度,通常有2種方法。
1是用Microsoft.VisualBasic.Len函數;2是用System.String類中的length屬性。
2者大致功能差不多,但當字串是nothing(c#是null),第一種方法會返回0,而第二種方法會報錯。
如下代碼:

1        Dim i As Int16
2
3        Dim strA As String
4        strA = Nothing
5        i = Microsoft.VisualBasic.Len(strA)   ‘i為0
6        i = strA.Length                       ‘拋出NullReferenceException異常
7

用reflector查看了一下Microsoft.VisualBasic.Len函數,原來函數是這樣寫的:

1Public Shared Function Len()Function Len(ByVal Expression As String) As Integer
2      If (Expression Is Nothing) Then
3            Return 0
4      End If
5      Return Expression.Length
6End Function

要想用System.String類中的length屬性實作類別似功能,可以手動加段程式,判斷一下字串的null值

        If strA Is Nothing Then
            i = 0
        Else
            i = strA.Length
        End If

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.