I'm trying to play a little with expression trees. I have an object with List<string> , and I want to build an expression tree that will add a value to this property, but I want to specify a value to add through Func . I am currently trying this ...
public static Action<T> CreateMethodAddObjectToList<T, C>(this Type type, string property, Func<C> ctorFunction) { PropertyInfo fieldInfo = type.GetProperty(property); if (fieldInfo == null) { return null; } ParameterExpression targetExp = Expression.Parameter(type, "target"); MemberExpression fieldExp = Expression.Property(targetExp, property); var method = fieldExp.Type.GetMethod("Add", BindingFlags.Public | BindingFlags.Instance); Expression<Func<C>> ctorExpression = () => ctorFunction();
the call looks like
var dummyObject = new DummyObject { IntProperty = 5 }; Action<DummyObject> setter = typeof (DummyObject).CreateMethodAddObjectToList<DummyObject, string>("StringList", () => "Test" );
source share