我在使用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当我赋值0,然后检索它时,它显示属性= nothing。
我需要属性有时为空,有时为零。有人能解释一下发生了什么吗?
发布于 2009-04-17 14:48:30
If _TicketCharge = Nothing没有做你期望的事情(挑衅的评论:和VB.NET一样;抱歉,伙计们,无法抗拒)。您需要If _TicketCharge Is Nothing或If Not _TicketCharge.HasValue
发布于 2009-04-17 14:53:30
进一步解释:
引用类型的"null“值和值类型的”默认“值在VB.Net中都不会有双重作用。当您使用"=“而不是" is”或"HasValue“时,您将强制它成为值类型角色,因此Nullable类将把它与它当前存储的值进行比较(包括在没有设置值的情况下抛出异常!)。由于小数的默认值为0,因此Get访问器顶部的比较结果为True。
发布于 2009-04-17 14:54:48
问题在于您比较_TicketChange以确定它是否具有值的方式。Nothing在VB.Net中有多种含义,因为它同时表示空值和引用类型。使用Nothing和Nullable执行布尔逻辑通常会导致意外的行为。
请改用_TicketChange.HasValue。
https://stackoverflow.com/questions/760675
复制相似问题