Microsoft.VisualBasic.Len函数和System.String类中的length属性的区别

来源:互联网 发布:知无知文化空间 编辑:程序博客网 时间:2024/05/17 00:03

环境:vs2003,vs.net
一般我求一个字符串的长度,通常有2种方法。
1是用Microsoft.VisualBasic.Len函数;2是用System.String类中的length属性。
2者大致功能差不多,但当字符串是nothing(c#是null),第一种方法会返回0,而第二种方法会报错。
如下代码:
        Dim i As Int16

        Dim strA As String
        strA = Nothing
        i = Microsoft.VisualBasic.Len(strA)   ‘i为0
        i = strA.Length                       ‘抛出NullReferenceException异常

用reflector查看了一下Microsoft.VisualBasic.Len函数,原来函数是这样写的:
Public Shared Function Len(ByVal Expression As String) As Integer
      If (Expression Is Nothing) Then
            Return 0
      End If
      Return Expression.Length
End Function

要想用System.String类中的length属性实现类似功能,可以手动加段程序,判断一下字符串的null值

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

原创粉丝点击