4

I use this method to get the value of a property in a method:

public static T Decrypt<T>(Func<T> prop, string username, string password)
{
    T value = prop();
    //do cool stuff with t
    return value;
}

I'm looking for a way to do the other way arround, set the value of my property

public static void Encrypt<T>(Func<T> prop, T value, string username, string password)
{
    //do stuff with value
    ??? set prop ???
}

I've searched and tried Expressions, but cloud not get it to work:

public static void Encrypt<T>(Expression<Func<T>> property, T value, string username, string password)
{
    //do stuff with value
    var propertyInfo = ((MemberExpression)property.Body).Member as PropertyInfo;
    propertyInfo.SetValue(property, value);
}
Christos
  • 53,228
  • 8
  • 76
  • 108
Richard
  • 14,427
  • 9
  • 57
  • 85

3 Answers3

7

Youd could change the Encrypt function like this:

public static void Encrypt<T>(Action<T> prop, T value, string username, string password)
{
  // awesome stuff before
  prop(value);
  // awesome stuff after
}

Then call Encrypt :

Encrypt(value => obj.Prop = value, 23, "", "");
Wolfgang Ziegler
  • 1,675
  • 11
  • 23
1

You stack in misunderstanding of how SetValue method behave, it takes an real object as first parameter which have the property which propertyInfo is described, so you need to take that object form expression instead of using expression itself, please take a look at the following answer on stakoverflow which may help you link to post

Community
  • 1
  • 1
Victor
  • 618
  • 4
  • 12
0

You can try this to set the property by name:

Type t = ctrl.GetType();
t.InvokeMember(propName, BindingFlags.Instance | BindingFlags.SetProperty |BindingFlags.Public, null, ctrl, new object[] { value });
becike
  • 195
  • 1
  • 8