我尝试使用表达式树进行操作。
我有一个包含 List<string>
的对象,我想构建一个表达式树来将值添加到该属性中,但我想通过 Func
指定要添加的值。
目前我正在尝试以下操作...
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();
// but this doesnt work because I can't use the ctorExpression in this way
var callExp = Expression.Call(fieldExp, method, ctorExpression);
var function = Expression.Lambda<Action<T>>(callExp, targetExp).Compile();
return function;
}
电话看起来像这样。
var dummyObject = new DummyObject { IntProperty = 5 };
Action<DummyObject> setter = typeof (DummyObject).CreateMethodAddObjectToList<DummyObject, string>("StringList", () => "Test" );