开发者

Passing a property into a method to change that property

开发者 https://www.devze.com 2023-01-04 23:21 出处:网络
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.

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开发者_JS百科(int index = 0; index < fields.Length)
{
    fieldPropertyMapping[index] = StripQuotes(fields[index]);
}


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.


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.


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
}
0

精彩评论

暂无评论...
验证码 换一张
取 消