Created
June 21, 2012 09:11
-
-
Save MrBretticus/2964767 to your computer and use it in GitHub Desktop.
Extension method to convert lambda property getter expression to a property setter delegate
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class ExpressionExtensions | |
{ | |
/// <summary> | |
/// Converts a lambda property getter expression to a property setter delegate. | |
/// For example: "o => o.MyProperty" to "o => o.MyProperty = newValue" | |
/// </summary> | |
public static Action<TProperty> ConvertGetterToSetter<TObject, TProperty>(this Expression<Func<TObject, TProperty>> expression, TObject o) { | |
var property = ((MemberExpression)expression.Body).Member as PropertyInfo; | |
Guard.Against(property == null, "Expression is not a property getter"); | |
var param = Expression.Parameter(typeof(TProperty), property.Name); | |
var call = Expression.Call(Expression.Constant(o), property.GetSetMethod(), new[] { (Expression)param }); | |
var viewSetter = Expression.Lambda<Action<TProperty>>(call, param).Compile(); | |
return viewSetter; | |
} | |
} | |
[TestClass] | |
public class When_using_extensions | |
{ | |
public class TestClass { public string TestProperty { get; set; } } | |
[TestMethod] | |
public void it_should_convert_a_getter_expression_to_a_setter_delegate() { | |
TestClass test = new TestClass(); | |
Expression<Func<TestClass, string>> getter = o => o.TestProperty; | |
Action<string> setter = getter.ConvertGetterToSetter(test); | |
setter("Test"); | |
Assert.AreEqual("Test", test.TestProperty); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment