首页 新闻 会员 周边 捐助

通过反射对带参数的属性赋值的问题

0
悬赏园豆:20 [已解决问题] 解决于 2010-01-14 09:42

有一个类:

代码
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 中显式转换。该如何做?

孔雀的主页 孔雀 | 初学一级 | 园豆:49
提问于:2010-01-07 10:46
< >
分享
最佳答案
0

做个类型转换

收获园豆:20
笑看风云淡 | 菜鸟二级 |园豆:245 | 2010-01-07 11:02
必须得指定转换目的类型进行显式转换吗?那有没有办法取得目标属性的数据类型后转换为该类型?我试过 CType(expression, typename) 的参数 typename 只能是明确给出的类型名,而不知道怎么动态的提供
孔雀 | 园豆:49 (初学一级) | 2010-01-08 10:54
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册