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

c# expression-trees generics lambda

Question

I am finding it difficult to develop a generic wrapper class that will use lambda expressions to invoke the functions.

The code appears as follows:

The Class of the Wrapper

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 that is enclosed:

public class Person
{
    public int GetPersonById(int bbb)
    {
        return bbb;
    }
}

In what location did I make the call?

var serviceWrapper = new Service<Person>(new Person());
serviceWrapper.Call(x =>x.GetPersonById(2),Console.WriteLine);

I suppose I need to attach the object instance that is "instance" to the method statement, but I'm not sure how.

I receive the following error when I execute this code:

Variable 'x' of type 'AsynCtry.Person' referenced from scope '', but it is not defined.

Exists a method to do this?

1
5
7/6/2013 8:31:40 AM

Accepted Answer

You can simply use delegates directly; you don't need expressions for this.

public void Call<U>(Func<T, U> aExpression, Action<U> returnClass)
{
    U result = aExpression(this.instance);
    returnClass(result);
}

If your method call is successful, then:

var serviceWrapper = new Service<Person>(new Person());
serviceWrapper.Call(x => x.GetPersonById(2), u => Console.WriteLine(u));
8
7/6/2013 12:23:31 AM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow