I am struggling to create a generic wrapper class which will call the methods with lambda expressions.
The code looks like this:
The Wrapper Class:
public class Service<T>
{
private T instance;
public Service(T param)
{
this.instance = param;
}
public void Call<U>(Expression<Func<T, U>> aExpression, Action<U> returnClass)
{
var methodCallExpr = aExpression.Body as MethodCallExpression
var lambdaToFunc = Expression.Lambda(methodCallExpr).Compile();
returnClass((U)lambdaToFunc.DynamicInvoke());
}
}
The class which is wrapped:
public class Person
{
public int GetPersonById(int bbb)
{
return bbb;
}
}
The place where I made the call:
var serviceWrapper = new Service<Person>(new Person());
serviceWrapper.Call(x =>x.GetPersonById(2),Console.WriteLine);
I guess i have to atatch the instance of the object which is "instance" to the method expression but I don't know how..
When I run this code i get this exception :
Variable 'x' of type 'AsynCtry.Person' referenced from scope '', but it is not defined.
Is there a way to do this?
You don't need expressions for this - just use delegates directly:
public void Call<U>(Func<T, U> aExpression, Action<U> returnClass)
{
U result = aExpression(this.instance);
returnClass(result);
}
Your method call should function, then:
var serviceWrapper = new Service<Person>(new Person());
serviceWrapper.Call(x => x.GetPersonById(2), u => Console.WriteLine(u));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With