tags:

views:

24

answers:

2

Suppose I have a method that passes in the name of a property (as a string) and the object that the property is on (as object).

How could I get the value of the property?

Here is some code to make it a bit more concrete:

protected override void Paint(Graphics g, Rectangle bounds, CurrencyManager source, int rowNum, Brush backBrush, Brush foreBrush, bool alignToRight)
{
   // The next line is made up code
   var currentValue = source.Current.CoolMethodToTakePropertyNameAndReturnValue(MappingName);

   // Paint out the retrieved value
   g.DrawString(currentValue.ToString() , _gridFont, new SolidBrush(Color.Black), bounds.Left + 1, bounds.Top);
}

MappingName is the name of the property I want to get the value for. What I need is CoolMethodToTakePropertyNameAndReturnValue.

Any ideas? I am running on the Compact Framework. I would also prefer to avoid reflection (but if that is my only recourse then so be it).

Thanks for any help.

A: 

I think reflection is the only way to accomplish that:

To Get  value
===============

foreach (PropertyInfo info in myObject.GetType().GetProperties())
{
   if (info.CanRead)
   {
      object o = propertyInfo.GetValue(myObject, null);
   }
}

To Set  value
================

object myValue = "Something";
if (propertyInfo.CanWrite)
{
    this.propertyInfo.SetValue(myObject, myValue, null);
}

Get fitting PropertyInfo:

=============================

foreach(PropertyInfo p in typeof(MyObject).GetProperties())
{
    if ( p.Name == "MyProperty") { return p }
}
MUG4N
+2  A: 

I would go with reflection

  foreach (PropertyInfo info in myObject.GetType().GetProperties())
  {
    if (info.CanRead && info.Name == MappingName)
    {
      return info.GetValue(myObject, null);
    }
  }  
alejandrobog