环境: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
Dim i As Int162

3
Dim strA As String4
strA = Nothing5
i = Microsoft.VisualBasic.Len(strA) ‘i为06
i = strA.Length ‘抛出NullReferenceException异常7

用reflector查看了一下Microsoft.VisualBasic.Len函数,原来函数是这样写的:
1
Public Shared Function Len(ByVal Expression As String) As Integer
2
If (Expression Is Nothing) Then
3
Return 0
4
End If
5
Return Expression.Length
6
End Function
Public Shared Function Len(ByVal Expression As String) As Integer2
If (Expression Is Nothing) Then3
Return 04
End If5
Return Expression.Length6
End Function
要想用System.String类中的length属性实现类似功能,可以手动加段程序,判断一下字符串的null值
If strA Is Nothing Then
i = 0
Else
i = strA.Length
End If


浙公网安备 33010602011771号