jeudi 26 mai 2016

VB.NET, why use reflection to get a value of an Objects property in this code

I've got a bit of sample code from the MSDN Magazine Dev 2008. "The ObservableCollection Class" by Ken Getz http://ift.tt/1ZNTfy9

It deals with raising and handling when a property value of a collection changes.

However, there's one bit I don't understand. The author uses reflection to obtain the Properties value of the affected Object in the collection. I don't understand why he does this when it can just be obtained by asking for the objects property value.

I suppose in the codes example the Author doesn't know which property has changed. I only need to monitor one property (name) so can I just grab it by calling myCustomer.name?

Is there another reason why refection is being used or is it just to generalise the code so it can show any change to any property in the class?

Private Sub HandlePropertyChanged( _
ByVal sender As Object, _
ByVal e As PropertyChangedEventArgs)

Dim propName As String = e.PropertyName
Dim myCustomer As Customer = CType(sender, Customer)

' Unfortunately, no one hands you the old property value, or the new 
' property value. You can use Reflection to retrieve the new property 
' value, given the object that raised the event and the name of the 
' property:
Dim propInfo As System.Reflection.PropertyInfo = _
  GetType(Customer).GetProperty(propName)
Dim value As Object =  propInfo.GetValue(myCustomer, Nothing)

MessageBox.Show(String.Format( _
  "You changed the property '{0}' to '{1}'", _
  propName, value))

End Sub





Aucun commentaire:

Enregistrer un commentaire