如果值为空,则将字符串设置为空

Setting a string to be empty if value is null

我不确定如何在这里搜索我要解决的问题。在我正在编写的程序中(在 VB.Net 中),我试图将从数据库中提取的值分配给结构中的不同变量。

现在我的问题是,有时从数据库中提取的某些值是 NULL,例如,并非每个 phone 号码都有扩展名。这就是我目前的代码:

Structure CustomerContact
    Public _name As String
    Public _email As String
    Public _fax As String
    Public _phone1 As String
    Public _phone2 As String
    Public _phone3 As String
    Public _ext1 As String
    Public _ext2 As String
    Public _ext3 As String
    Public _type1 As String
    Public _type2 As String
    Public _type3 As String
End Structure

    Dim contactData As DataTable = CustomerDBFunctions.GetCustomerContacts(Customer)
    For Each row As DataRow In contactData.Rows
        If contacts.Count < 1 Then
            contacts.Add(New CustomerContact With {
                            ._name = row.Item("FullName").ToString() & " (" & row.Item("ContactType").ToString() & ")",
                            ._email = row.Item("Email").ToString(),
                            ._fax = row.Item("Fax").ToString(),
                            ._phone1 = row.Item("Phone").ToString(),
                            ._ext1 = row.Item("Extension").ToString(),
                            ._type1 = row.Item("PhoneType").ToString()})
        End If
    Next

现在,当数据库中的值为 NULL 时,我收到错误消息,因为它无法将 NULL 值分配给字符串。我想在存在 NULL 值的情况下将变量的值设置为 ""。我只是不确定如何编码。

从技术上讲,问题不在于该列为空。 String 是一个引用类型,所以它可以是空的(但是,如果它是空的,你无论如何都不能调用它的 ToString )。实际发生的是 ADO.NET 总是 returns DBNull.Value 对于行包含空值的所有列。

你可以这样检查:

If row.Item("Phone") <> DBNull.Value Then
    customerContact._phone1 = row.Item("Phone")?.ToString()
End If

请注意,我在调用 ToString 时使用 ?. 而不是 . 以防万一该列实际上为空而不是 DbNull.Value。这样做的原因是我不知道你用什么样的代码来填充DataTable。如果是 ADO.NET 填充它,它永远不会为空,但如果它是通过其他方式填充它的自定义代码,它可能会在其中得到实际的空值。

由于您使用 DataTable 到 return 值,它有一个方便的 IsNull 方法供您使用,它稍微清理了代码:

If Not row.IsNull("Phone") Then
    customerContact._phone1 = row.Item("Phone")?.ToString()
End If

显然,如果您经常这样做,最好将其包装成一个可重用的函数。另外,如果你想把它缩短成一行,你可以这样做:

._phone1 = If(row.IsNull("Phone"), row.Item("Phone")?.ToString(), Nothing)

字符串连接可用于将 Nothing 转换为 ""(我的回答中的其他替代方案 here

._fax = row!Fax & "",