有一个类:
Public Class MyData
Private _data(4) As Double
Public Property Data(ByVal ii As Int32) As Double
Get
Return _data(ii)
End Get
Set(ByVal value As Double)
_data(ii) = value
End Set
End Property
Public Sub New()
For i As Int32 = 0 To 4
_data(i) = i + 1
Next
End Sub
End Class
现在我采用反射来访问这个属性:
Public md As MyData
Public Sub Main()
md = New MyData()
Dim d(4) As Double
For i As Int32 = 0 To 4
d(i) = GetData(i)
Next
For i As Int32 = 0 To 4
SetData(i, 2 * d(i))
MessageBox.Show(GetData(i).ToString)
Next
End Sub
Public Function GetData(ByVal ii As Int32) As Double
Dim t As Type = md.[GetType]()
Return t.InvokeMember("Data", Reflection.BindingFlags.GetProperty, Nothing, md, New Object(){ii})
End Function
SetData 的实现有下面三种方法:
Public Sub SetData0(ByVal ii As Int32, ByVal value As Int32)
Dim t As Type = [GetType]()
t.InvokeMember("Data", Reflection.BindingFlags.SetProperty, Nothing, md, New Object(){ii, value})
End Sub
Public Sub SetData1(ByVal ii As Int32, ByVal value As Int32)
Dim t As Type = [GetType]()
Dim p As PropertyInfo = t.GetProperty("Data")
p.SetValue(md, value, New Object(){ii})
End Sub
Public Sub SetData2(ByVal ii As Int32, ByVal value As Int32)
Dim t As Type = [GetType]()
Dim p As PropertyInfo = t.GetProperty("Data")
Dim m As MethodInfo = p.GetSetMethod()
m.Invoke(md, New Object(){ii, value})
End Sub
为了重现问题,我故意把将要设置给属性的值设为 Int32 而不是 Double,因为VB在传入参数的时候自己会进行隐式转换
SetData0 用 Type.InvekeMenber,将索引和要设置的值作为参数传入。
出错提示:未找到方法"MyData.Data"。
SetData1 和 SetData2 分别用 PropertyInfo.SetValue 和 MethodInfo.Invoke
出错提示:类型"System.Int32"的对象无法转换为类型"System.Double"。看来用反射调用方法时不会调用隐式转换?
由于我的实际数据类将面对多种不同类型的属性,所以不能简单的在 SetData 中显式转换。该如何做?
做个类型转换