3

我在使用 Vb.net 3.5 的类上有一个可为空的公共属性:

    Public Property TicketCharge() As Nullable(Of Decimal)
        Get
            If _TicketCharge = Nothing Then
                Return Nothing
            Else
                Return _TicketCharge
            End If
        End Get
        Set(ByVal value As Nullable(Of Decimal))
            If value.HasValue Then _TicketCharge = value
        End Set
    End Property

有一种分配值的方法。它工作正常,除非我尝试将值 0(零)分配给它。

    If FundBuySell = "Exchange $" Or FundBuySell = "Exchange Shares" Then
            TicketCharge = 0
    Else

当我分配零然后检索它时,它显示属性 = 无。

我需要属性有时为空,有时为零。有人可以解释发生了什么吗?

4

4 回答 4

2

没有按照If _TicketCharge = Nothing您的预期进行(煽动性评论:VB.NET 总是如此;对不起,伙计们,无法抗拒)。你要么需要If _TicketCharge Is Nothing要么If Not _TicketCharge.HasValue

于 2009-04-17T14:48:30.123 回答
1

进一步解释:

在 VB.Net 中,没有什么可以作为引用类型的“空”值和值类型的“默认”值来实现双重职责。当您使用“=”而不是“Is”或“HasValue”时,您将其强制为值类型角色,因此 Nullable 类会将其与其当前存储的值进行比较(包括如果没有值则抛出异常放!)。由于 Decimal 的默认值为 0,因此访问器顶部的比较结果Get为 True。

于 2009-04-17T14:53:30.080 回答
1

问题在于您比较 _TicketChange 以确定它是否具有值的方式。Nothing 在 VB.Net 中具有多种含义,因为它既代表空值又代表引用类型。使用 Nothing 和 Nullable 执行布尔逻辑通常会导致意外行为。

而是使用 _TicketChange.HasValue。

于 2009-04-17T14:54:48.313 回答
1

最后这工作:

If Not IsDBNull(var) 
于 2012-03-01T22:00:56.513 回答