How to get the string (source code) that generated the lambda expression?

(for LISP hackers in short: I'm looking for the equivalent of LISP -quote in C #)

I am trying to write a meaningful ToString method for a class that has a Func member. Advanced API users can set this element using the setter method, for example

myClassObject.SetFunction( (x) => x*x );

Now when I use the ToString method in the member, it only returns

System.Func<double,double>

which is not very useful. What would be helpful

"(x) => x*X"

Is there any (preferred simple) way to do this?

Thanks for any help or comments.

Edit: fixed some typos

+5
source share
3 answers
Expression<Func<double,double>> expr = x => x * x;
string s = expr.ToString(); // "x => (x * x)"
+7
source
+1

, , . :

private Expression<Func<double, double>> myFunc;
private Func<double, double> cachedDelegate; 

public void SetFunc(Expression<Func<double,double>> newFunc)
{
    this.myFunc = newFunc;
    this.cachedDelegate = null;
}

public double ExecFunc(double x)
{
    if (this.myFunc != null)
    {
        if (this.cachedDelegate != null)
        {
            return this.cachedDelegate(x);
        }
        else
        {
            this.cachedDelegate = this.myFunc.Compile();
            return this.cachedDelegate(x);
        }
    }

    return 0.0;
}

public string GetFuncText()
{
    if (this.myFunc != null)
    {
        return this.myFunc.ToString();
    }
    return "";
}

-, . , .

In addition, this approach means that users should use lambda, as method groups are not converted to Expression<Func<>>. However, this does not cause much concern, because instead of transferring the MyMethoduser could go through x => MyMethod(x).

The call code looks something like this:

myObject.SetFunc(x => 2*x);
Console.WriteLine(myObject.GetFuncText());

In conclusion, we note that the above example is not thread safe, so if you expect methods to be called from multiple threads, some kind of synchronization would be appropriate.

+1
source

All Articles