如何为作为Object传递的Double类型的变量赋值



我正在尝试为全局变量赋值,该变量的Property类型为Double。该Property被传递为Object,并且分配失败。

在下面的示例代码中,该值从未分配给实际对象,而是仅在本地分配:

Public Class Form1
    Friend Home As New Building
    Private Sub AssignValues() Handles Me.Load
        'Objects of different types are added to a list
        Dim listObjects As New List(Of Object)
        listObjects.Add(Home.Surface)
        'All the Objects in listObjects are assigned a value that
        'is stored as String
        For Each o As Object In listObjects
            SetProperty(o, "45.6")
            Debug.Print("Surface = " & Home.Surface.ToString)
        Next
    End Sub
    Private Sub SetProperty(ByRef Variable As Object, ByVal Value As String)
        Select Case Variable.GetType
            Case GetType(Double)
                Variable = CDbl(Value)
            Case Else
                '...
        End Select
    End Sub
End Class
Public Class Building
    Dim _surface As Double = 0
    Public Property Surface As Double
        Get
            Return _surface
        End Get
        Set(ByVal value As Double)
            _surface = value
        End Set
    End Property
End Class

程序总是输出Surface = 0而不是45.6。我做错了什么?

正如这里所建议的,我试图通过Variable作为参考,但没有成功。我也读过关于使用反射的文章,但应该有比这更简单的东西。。。

将home.surface添加到列表时,将double的副本添加到列表中,然后调整该副本。把手表贴在"o"上,看看它在home.surface保持不变时会发生什么变化。

如果你想使用反射,试着沿着这些线做一些事情。

Dim prop As Reflection.PropertyInfo = o.GetType().GetProperty("Surface")
prop.SetValue(o, 45.6)

使用Variable.GetType,您将始终获得Object,因为这是Variable的类型。使用Object可以将其转换/强制转换为不同的类型(如Double)。

确定Object来源的"原始类型"的最佳方法是包含一个额外的变量来告诉它。另一种选择可能是将给定的Object转换为目标Type,看看它是否为空/不会触发错误。但第二种选择并不太准确,主要是在处理Doubles/Integers等"等效类型"时。

最新更新