摘要:動態呼叫Object的Property (Dynamic Invoke)
之前有專案中有用到動態設定及讀取物件的值,是透過Reflection的方式,Code如下,
'設定物件值
Sub SetControlPropertyValue(ByRef rCtrl As Control, ByVal vstrName As String, ByRef rVaue As Object)
Dim pi As System.Reflection.PropertyInfo = rCtrl.GetType.GetProperty(vstrName)
If IsNothing(pi) = False Then
Dim objValue As Object
objValue = System.ComponentModel.TypeDescriptor.GetConverter(pi.PropertyType).ConvertFrom(rVaue)
pi.SetValue(rCtrl, objValue, Nothing)
End If
End Sub
Sub SetControlPropertyValue(ByRef rCtrl As Control, ByVal vstrName As String, ByRef rVaue As Object)
Dim pi As System.Reflection.PropertyInfo = rCtrl.GetType.GetProperty(vstrName)
If IsNothing(pi) = False Then
Dim objValue As Object
objValue = System.ComponentModel.TypeDescriptor.GetConverter(pi.PropertyType).ConvertFrom(rVaue)
pi.SetValue(rCtrl, objValue, Nothing)
End If
End Sub
'取得物件的屬性值
Public Function GetControlPropertyValue(ByRef rCtrl As Control, ByVal vstrName As String) As Object
Dim pi As System.Reflection.PropertyInfo = rCtrl.GetType.GetProperty(vstrName)
If IsNothing(pi) = False Then
Return pi.GetValue(rCtrl, Nothing)
Else
Return String.Empty
End If
End Function
Public Function GetControlPropertyValue(ByRef rCtrl As Control, ByVal vstrName As String) As Object
Dim pi As System.Reflection.PropertyInfo = rCtrl.GetType.GetProperty(vstrName)
If IsNothing(pi) = False Then
Return pi.GetValue(rCtrl, Nothing)
Else
Return String.Empty
End If
End Function
後來在Codeproject說使用Reflection.Emit會比較快,所以就改成以下的Code
'設定物件值
Sub SetControlPropertyValue(ByRef rCtrl As Control, ByVal vstrName As String, ByRef rVaue As Object)
Dim propAccessor As IMemberAccessor = MemberAccessor.Make(rCtrl.GetType, vstrName)
propAccessor.Set(rCtrl, rVaue)
End Sub
Sub SetControlPropertyValue(ByRef rCtrl As Control, ByVal vstrName As String, ByRef rVaue As Object)
Dim propAccessor As IMemberAccessor = MemberAccessor.Make(rCtrl.GetType, vstrName)
propAccessor.Set(rCtrl, rVaue)
End Sub
'取得物件的屬性值
Public Function GetControlPropertyValue(ByRef rCtrl As Control, ByVal vstrName As String) As Object
Dim propAccessor As IMemberAccessor = MemberAccessor.Make(rCtrl.GetType, vstrName)
Return propAccessor.Get(rCtrl)
End Function
Public Function GetControlPropertyValue(ByRef rCtrl As Control, ByVal vstrName As String) As Object
Dim propAccessor As IMemberAccessor = MemberAccessor.Make(rCtrl.GetType, vstrName)
Return propAccessor.Get(rCtrl)
End Function
程式可在以下的URL download哦!
http://www.codeproject.com/KB/cs/DynamicCodeVsReflection.aspx
Hi,
亂馬客Blog已移到了 「亂馬客 : Re:從零開始的軟體開發生活」
請大家繼續支持 ^_^