Get the parameter value from a Linq Expression
I have the following class
public class MyClass
{
public bool Delete(Product product)
{
// some code.
}
}
Now I have a helper class that looks like this
public class Helper<T, TResult>
{
Type type;
string method;
Type[] argTypes;
object[] argValues;
public Helper(Expression<Func<T, TResult>> expression)
{
var body =
(System.Linq.Expressions.MethodCallExpression)expression.Body;
this.type = typeof(T);
this.method = body.Method.Name;
this.argTypes = body.Arguments.Select(x => x.Type).ToArray();
this.argValues = ???
}
public void Invoke(T instance)
{
type.GetMethod(method, argTypes).Invoke(instance, args);
}
}
The idea ist to use this code from somewhere:
public void SomeMethod()
{
var product = GetProduct(1);
var helper = new Helper<MyClass>(x => x.Delete(product);
var instance = new MyClass();
helper.Invoke(instance);
}
The point where I am stuck is how to extract the arguments from the
expression itself.
I found this way
((ConstantExpression)((MemberExpression)body.Arguments[0]).Expression).Value
which seems to be an object type with a field "product" but I believe
there must be a simpler solution.
Any suggestions.
No comments:
Post a Comment