使用可空数据类型的属性分配文本框文本

Nic*_*dum 3 vb.net controls nullable

出于某种原因,当我尝试将可为空的十进制数据类型的属性分配给文本框文本时,我遇到了错误.

例如,我有这个Product类:

Public Class Product
    Public Property ProductId As Integer
    Public Property ProductName As String
    Public Property [Variant] As String
    Public Property PackSize As Decimal?
End Class
Run Code Online (Sandbox Code Playgroud)

并且a的实例Product具有[Variant]NothingPackSizeNothing.

当我尝试将[Variant]值分配给文本框时,如下所示:

VariantTextBox.Text = mProduct.[Variant]
Run Code Online (Sandbox Code Playgroud)

它工作正常.

但是,当我尝试将PackSize值分配给文本框时,如下所示:

PackSizeTextBox.Text = mProduct.PackSize
Run Code Online (Sandbox Code Playgroud)

它会抛出此消息的异常:

可以为空的对象必须具有值.

我不明白为什么当我这样做时会发生这种情况:

PackSizeTextBox.Text = Nothing
Run Code Online (Sandbox Code Playgroud)

没有任何错误.

我尝试过其他方式做事:

PackSizeTextBox.Text = If(mProduct.PackSize, Nothing)
PackSizeTextBox.Text = If(mProduct.PackSize IsNot Nothing, mProduct.PackSize, Nothing)
PackSizeTextBox.Text = If(mProduct.PackSize.HasValue, mProduct.PackSize, Nothing)
Run Code Online (Sandbox Code Playgroud)

但他们都抛出同样的错误.

但是,当我稍微调整它们时:

PackSizeTextBox.Text = If(mProduct.PackSize, "")
PackSizeTextBox.Text = If(mProduct.PackSize IsNot Nothing, mProduct.PackSize, "")
PackSizeTextBox.Text = If(mProduct.PackSize.HasValue, mProduct.PackSize, "")
Run Code Online (Sandbox Code Playgroud)

他们奇怪地工作得很好.

最后,我真的不喜欢做长If语句只是为了获得可以为空的数据类型属性的值,所以我只是这样做:

PackSizeTextBox.Text = mProduct.PackSize?.ToString
Run Code Online (Sandbox Code Playgroud)

我希望有人可以向我解释我遇到的错误.谢谢!

jmc*_*ney 6

a的Text属性TextBox是类型,String因此唯一可以分配给它的是a String.如果您拥有Option Strict Off并分配除了a之外的其他内容,String则系统将隐式调用ToString它.这意味着:

PackSizeTextBox.Text = mProduct.PackSize
Run Code Online (Sandbox Code Playgroud)

与此基本相同:

PackSizeTextBox.Text = mProduct.PackSize.Value.ToString()
Run Code Online (Sandbox Code Playgroud)

为什么你当你做了错误消息,则应该是显而易见的mProduct.PackSizeNothing.

所有这些:

PackSizeTextBox.Text = If(mProduct.PackSize, Nothing)
PackSizeTextBox.Text = If(mProduct.PackSize IsNot Nothing, mProduct.PackSize, Nothing)
PackSizeTextBox.Text = If(mProduct.PackSize.HasValue, mProduct.PackSize, Nothing)
Run Code Online (Sandbox Code Playgroud)

无法工作,因为If运算符基本上是通用的,因为返回的两个值必须是相同的类型.因此,所有Nothing返回值都会隐式转换为Decimal?值,最终必须String以完全相同的方式将其隐式转换为完全相同的方式.

你最终得到的代码:

PackSizeTextBox.Text = mProduct.PackSize?.ToString
Run Code Online (Sandbox Code Playgroud)

是正确的代码,因为您明确地将非a的内容转换String为a String以将其分配给String属性.这正是你应该做的事情以及你必须要做的事情Option Strict On,你绝对应该这样做.

Option Strict Off默认情况下,任何VB.NET开发人员都是初学者,他们不了解更好或更糟糕的开发人员.打开它On现在在你的项目属性,并在你的IDE选项,因此它On在默认情况下在所有未来的项目.您应该只Off在特别需要延迟绑定时才转动它,即使这样,也只能在仅包含需要后期绑定的特定代码的部分类文件中.