【发布时间】:2013-06-02 16:03:24
【问题描述】:
我正在 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)
如果 "container" Is Date 会调用到
public function AsignAux(byref container as Date, value as string)
这很好用,.NET 无论如何都知道 Object 的类型,因为调用正确的重载函数。 所以我想找到(就像 .NET 一样)一种方法来确定具有空值的 Nullable 对象的类型。
谢谢
【问题讨论】:
标签: .net vb.net reflection types casting