代码之家  ›  专栏  ›  技术社区  ›  John Sonmez

Passing a property into a method to change that property

  •  5
  • John Sonmez  · 技术社区  · 15 年前

    不确定这是否可行,但我想做的是:

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

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

    我的最终结果代码看起来像:

    for(int index = 0; index < fields.Length)
    {
        fieldPropertyMapping[index] = StripQuotes(fields[index]);
    }
    
    3 回复  |  直到 15 年前
        1
  •  6
  •   Adam Robinson    15 年前

    PropertyInfo 班级。我不能完全确定您的代码在做什么,但是反射性设置属性值的一般示例将是:

    object targetInstance = ...; // your target instance
    
    PropertyInfo prop = targetInstance.GetType().GetProperty(propertyName);
    
    prop.SetValue(targetInstance, null, newValue);
    

    You could, however, pass an Action<T> 相反,如果您知道代码中某个点的属性。例如:

    YourType targetInstance = ...;
    
    Action<PropertyType> prop = value => targetInstance.PropertyName = value;
    
    ... // in your consuming code
    
    prop(newValue);
    

    或者,如果你知道它的类型,当你调用它,但是你没有这个实例,你可以把它变成一个 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);
    

    Action<object> and cast it to the proper property type within the lambda, but this should work either way.

        2
  •  2
  •   LBushkin    15 年前

    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. 创建一个具有该属性的闭包的ActualDe委托,并将其传递到方法中。
        3
  •  0
  •   Derick Bailey    15 年前

    可以使用反射获得类的属性:

    var properties = obj.GetType().GetProperties();
    
    foreach (var property in properties)
    {
      //read / write the property, here... do whatever you need
    }