Tony Gong的技术Blog  
技术旅途中蹒跚的行者

环境: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(ByVal Expression As StringAs Integer
2      If (Expression Is NothingThen
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
posted on 2006-04-06 16:55  Tony.Gong  阅读(662)  评论(0编辑  收藏  举报