我正在尝试在 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 的类型。
谢谢