将属性传递给方法以更改该属性

时间:2010-06-25 18:53:15

标签: c# reflection delegates lambda properties

不确定这是否可行,但这是我要做的事情:

我希望有一个字典,其中包含列索引到用于填充该索引的属性名称的映射。

在我的代码中,我将遍历一个数组,如果是字符串并使用字典来查找它应该映射到哪一列。

我的最终结果代码如下:

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

3 个答案:

答案 0 :(得分:6)

要专门做你要求的事情,你必须使用反射(当你标记你的问题时)来做这件事。看看PropertyInfo课程。我不完全确定你的代码在做什么,但是反思性地设置属性值的一般例子是:

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

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

prop.SetValue(targetInstance, null, newValue);

但是,如果您在代码中的某个位置知道属性,则可以传递Action<T>。例如:

YourType targetInstance = ...;

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

... // in your consuming code

prop(newValue);

或者,如果您在调用它时知道了类型但没有实例,则可以将其设为Action<YourType, PropertyType>。这也会阻止创建一个闭包。

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

... // in your consuming code

prop(instance, newValue);

要使其完全通用(“非特定”中的“通用”,而不是泛型),您可能必须将其设为Action<object>并将其转换为适当的属性类型。 lambda,但这应该有效。

答案 1 :(得分:2)

您有几个选择:

  1. 使用反射。存储并将PropertyInfo对象传递给方法,并通过反射设置它的值。
  2. 使用该属性的闭包创建一个ActionDelegate,并将其传递给方法。

答案 2 :(得分:0)

您可以使用反射来获取类的属性:

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

foreach (var property in properties)
{
  //read / write the property, here... do whatever you need
}
相关问题