Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create a generic wrapper class which will call the methods with lambda expressions

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?

like image 506
Alexandru Beu Avatar asked Jul 06 '13 00:07

Alexandru Beu


1 Answers

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));
like image 62
Reed Copsey Avatar answered Nov 14 '22 21:11

Reed Copsey