views:

76

answers:

3

Not sure if this is possible, but here is what I am trying to do:

I want to have a dictionary that contains a mapping of a column index to a property name used to populate that index.

In my code I will loop through an array if strings and use the dictionary to look up which column it should map to.

My end result code would look like:

for(int index = 0; index < fields.Length)
{
    fieldPropertyMapping[index] = StripQuotes(fields[index]);
}
+2  A: 

You have a couple of choices:

  1. Use reflection. Store and pass a PropertyInfo object into the method and set it's value through reflection.
  2. Create an ActionDelegate with a closure to that property and pass that into the method.
LBushkin
+1 for the Action approach.
Anthony Pegram
+3  A: 

To do what you're asking specifically, you'll have to use reflection (as you tagged your question) to do this. Have a look at the PropertyInfo class. I'm not entirely certain what your code is doing, but a general example of reflectively setting a property value would be:

object targetInstance = ...; // your target instance

PropertyInfo prop = targetInstance.GetType().GetProperty(propertyName);

prop.SetValue(targetInstance, null, newValue);

You could, however, pass an Action<T> instead, if you know the property at some point in the code. For example:

YourType targetInstance = ...;

Action<PropertyType> prop = value => targetInstance.PropertyName = value;

... // in your consuming code

prop(newValue);

Or, if you know the type when you call it but you don't have the instance, you could make it an Action<YourType, PropertyType>. This also would prevent creating a closure.

Action<YourType, PropertyType> prop = (instance, value) => instance.PropertyName = value;

... // in your consuming code

prop(instance, newValue);

To make this fully generic ("generic" as in "non-specific", not as in generics), you'll probably have to make it an Action<object> and cast it to the proper property type within the lambda, but this should work either way.

Adam Robinson
Your second example was exactly what I was looking for, thanks. I was dancing all around that solution, but couldn't get it for some reason.
John Sonmez
A: 

you can use reflection to get the properties for a class:

var properties = obj.GetType().GetProperties();

foreach (var property in properties)
{
  //read / write the property, here... do whatever you need
}
Derick Bailey