1

我正在尝试在 VB.NET(框架 3.5)中获取具有 Nothing 值(其默认值)的 Nullable 属性的类型,以了解如何制作 CType。代码将是这样的:

Class DinamicAsign
Public Property prop As Integer?
Public Property prop2 As Date?

Public Sub New()
    Asign(prop, "1")
    Asign(prop2, "28/05/2013")
End Sub

Public Sub Asign(ByRef container As Object, value As String)
    If (TypeOf (container) Is Nullable(Of Integer)) Then
        container = CType(value, Integer)
    ElseIf (TypeOf (container) Is Nullable(Of Date)) Then
        container = CType(value, Date)
    End If
End Sub
End Class

此代码无法正常工作。问题是如何知道“容器”的类型。

如果“prop”有一个值(“prop”不是什么),则此代码有效:

If (TypeOf(contenedor) is Integer) then...
If (contenedor.GetType() is Integer) then...

但是如果值什么都没有,我不知道如何获取类型。我试过这种方法,但不工作:

container.GetType() 

TypeOf (contenedor) is Integer 

TypeOf (contenedor) is Nullable(of Integer) 

我知道有人会回应说“容器”什么都不是,因为它没有引用任何对象,而且你不知道类型。但这似乎是错误的,因为我找到了解决这个问题的技巧:创建一个重载函数来进行强制转换,这样:

Class DinamicAsign2
Public Property prop As Integer?
Public Property prop2 As Date?

Public Sub New()
    Asignar(prop, "1")
    Asignar(prop2, "28/05/2013")
End Sub

Public Sub Asignar(ByRef container As Object, value As String)
    AsignAux(container, value)
End Sub

Public Sub AsignAux(ByRef container As Integer, value As String)
    container = CType(value, Integer)
End Sub

Public Sub AsignAux(ByRef container As Decimal, value As String)
    container = CType(value, Decimal)
End Sub
End Class

如果“容器”是整数,它将调用

public function AsignAux(byref container as Integer, value as string)

如果“容器”是日期将调用

public function AsignAux(byref container as Date, value as string)

这工作正常,.NET 无论如何都知道 Object 的类型,因为调用正确的重载函数。所以我想找出(就像 .NET 一样)一种方法来确定没有任何值的 Nullable Object 的类型

谢谢

4

1 回答 1

3

当 aNullable(Of T)变为 时Object,类型数据将丢失:它要么变为普通 old Nothing,要么变为它所代表的类型,例如Integer。您也许可以更改方法来执行此操作:

Public Sub Asign(Of T As Structure)(ByRef container As Nullable(Of T), value As String)
    ' T is Integer or Date, in your examples
    container = System.Convert.ChangeType(value, GetType(T))
End Sub

如果没有,您将不得不在其他地方记录类型,并将其传递给您的方法。

有关为什么将装箱/拆箱设置为以这种方式工作的一些信息,请参阅装箱/拆箱 Nullable 类型 - 为什么使用此实现?. 简而言之,将可空类型作为Object.

于 2013-06-06T15:15:14.603 回答