什么是最简洁的方法来处理这是否Nothing /空字符串检查?

时间:2011-04-01 18:09:00

标签: vb.net

查看TelephoneNumber属性中是否有一些不会修剪为空字符串的字符串的最佳方法是什么?我讨厌在Nothing上使用Trim VB.NET函数,只要在TelephoneNumber为Nothing时给我一个空字符串。

   Public Class TelephoneNumberType

        Public Property TelephoneNumber() As String

    End Class

  Public Class Form1

    Private _PhoneObj As BusinessObjects.TelephoneNumberType

     Public Sub MySub


        If _PhoneObj IsNot Nothing AndAlso _
           _PhoneObj.TelephoneNumber isNot Nothing AndAlso _
           _PhoneObj.TelephoneNumber.Trim <> String.Empty Then
           MessageBox.Show("I have a non blank phone!")
        End If

      End Sub

    End Class

编辑:

查看接受的答案,然后按以下方式调用

If _PhoneObj IsNot Nothing AndAlso _
   _PhoneObj.TelephoneNumber.IsNullOrEmpty Then
    MessageBox.Show("I have a non blank phone!")
End If

让我感到困惑的是,“IsNullOrEmpty”函数作为字符串实例的扩展方法,即使String是NOTHING也是如此。为什么这个扩展方法可以工作,但直接遵循 - .NET代码引发异常?

Dim s as string


If s.trim() = "" Then   
    Message.Box.Show("This will never print") 
End If

4 个答案:

答案 0 :(得分:6)

您可以通过调用String.IsNullOrWhiteSpace(需要.NET 4)来替换它:

If _PhoneObj IsNot Nothing AndAlso Not String.IsNullOrWhitespace(_PhoneObj.TelephoneNumber) Then
   MessageBox.Show("I have a non blank phone!")
End If

答案 1 :(得分:1)

像我一样使用StringExtensions模块。我为我的项目创建了这个:

Option Explicit On
Option Strict On

Imports System.Runtime.CompilerServices

Public Module StringExtensions

    <Extension()> _
    Public Function IsNullOrEmpty(ByVal s As String) As Boolean
        Return s Is Nothing OrElse s.Trim.Length.Equals(0)
    End Function

    <Extension()> _
    Public Function IsNotNullOrEmpty(ByVal s As String) As Boolean
        Return s IsNot Nothing AndAlso s.Trim.Length > 0
    End Function

End Module

这允许您执行以下操作:

Dim s1 As String = Nothing
Dim s2 As String = String.Empty
Dim s3 As String = "123"

If s1.IsNullOrEmpty Then
    'Do Something
End If 

If s2.IsNullOrEmpty Then
    'Do Something
End If

If s3.IsNotNullOrEmpty Then
    'Do Something
End If

所有这些都非常简单易用。

编辑:

这是我为我的需要而做的一个伟大的帮助扩展,我将为你投入:

    <Extension()> _
    Public Function ContainsAny(ByVal s As String, ByVal ParamArray values As String()) As Boolean
        If s.IsNotNullOrEmpty AndAlso values.Length > 0 Then
            For Each value As String In values
                If s.Contains(value) Then Return True
            Next
        End If

        Return False
    End Function

答案 2 :(得分:1)

最简单的简洁代码肯定是

If Trim(str) = "" Then 
  '' Nothing, "" or whitespace 

可以工作,因为VB将Nothing视为等同于“”,并且因为Microsoft.VisualBasic函数Trim是一个函数,而不是实例方法,所以它对Nothing很满意

答案 3 :(得分:0)

if(!string.IsNullorEmpty(str) && str.Trim() != string.Empty)
//non empty string
else
//emptry string
相关问题