【问题标题】:How to check for Null on a `SqlString` in VB.Net 2.0?如何在 VB.Net 2.0 中检查“SqlString”上的 Null?
【发布时间】:2017-10-31 23:16:42
【问题描述】:

我有一个 SqlString 类型的属性,它当前返回 Null。

_oData.Customer.Name

以下是我尝试过但没有奏效的以下检查。

IsNothing(_oData.Customer.Name)
_oData.Customer.Name.IsNull
_oData.Customer.Name.Value IsNot Nothing
_oData.Customer.Name = Nothing

每一个都会导致以下错误。如何真正检查值为 Null 的值。

数据为空。不能对 Null 值调用此方法或属性。

_oData.Customer 具有其他属性的值。

编辑

添加具有 name 属性的类。这是它在Customer 类中的定义方式

   Private mName As SqlTypes.SqlString

   Public Property Name() As SqlTypes.SqlString
        Get
            Return mName
        End Get
        Set(ByVal value As SqlTypes.SqlString)
            mName = value
        End Set
    End Property

在 SqlTypes 命名空间中看到的 SqlString

EDIT-2

好的似乎是处理三元操作方式的问题

这行得通

If _oData.Customer.Name.IsNull Then
    CName = ""
Else
    CName = _oData.Customer.Name
End If

这不是

CName = IIf(_oData.Customer.Name.IsNull, "", _oData.Customer.Name.Value)

谁能告诉我为什么这在使用三元运算时不起作用?

【问题讨论】:

  • SqlString 是什么意思没有这样的 NET 数据类型。如果您的意思是DbType.String,那么它只是一个字符串。不知道你在问什么,但String.IsNullOrEmpty() 可能是你所追求的
  • 您确定 Customer 或 _oData 不为空吗? (无)
  • @Steve:是的,这是我检查的第一件事。它上面的其他属性都有值
  • @Plutonix: 它在C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Data.dll System.Data.SqlTypes 命名空间下
  • 令人惊讶的是_oData.Customer.Name.IsNull 的值是True,但是当我调用它时,它返回的错误与我上面的帖子相同。

标签: vb.net ado.net .net-2.0


【解决方案1】:

你应该使用 Microsoft.VisualBasic.Information.IsDBNull() 方法:

If IsDBNull(_oData.Customer.Name) Then

【讨论】:

  • 仍然遇到同样的错误Data is Null. This method or property cannot be called on Null values.
  • 检查上面帖子中的编辑2
  • 这很讽刺。但众所周知,Because the IIf function does not use short-circuit evaluation, it always evaluates all three of its arguments. (link)
  • 啊!不知道,来自 C# 背景。谢谢。谜团解开了。
猜你喜欢
  • 2010-09-27
  • 1970-01-01
  • 1970-01-01
  • 2014-07-16
  • 1970-01-01
  • 2011-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多