开发者

How can one "scan" a lambda expression in C#?

Is is possible to scan a function provided as a lamba expression to figure out the nature of the function at runtime?

Example:

class Program
{
    static void Main(string[] args)
    {
        Examples开发者_如何转开发 example = new Examples(x => x ^ 2 + 2);
    }
}

public class Examples
{
    public Examples(Func<dynamic, dynamic> func)
    {
        // How can I scan "func" here to figure out that it is defined as "x => x ^ 2 + 2" instead of, say, as "x => Math.Exp(x)"?
    }
}


You need to use expression trees, like this:

public Examples(Expression<Func<dynamic, dynamic>> func) {
    ...
}

For more information, see here.


What you are after is an expression tree, you could change your Example method signature to....

public Examples(Expression<Func<dynamic, dynamic>> exp)
{
  // Visit the expression in here...
}


you can examine the syntactical structure of a LambdaExpression by looking at the Parameters property and Body property. The Body is an Expression node representing the root of the function body's abstract syntax tree.

or use an ExpressionVisitor, which traverses the nodes in the expression tree. Example code here: http://msdn.microsoft.com/en-us/library/bb882521.aspx


Take a look at this link:

http://msdn.microsoft.com/en-us/library/bb397951.aspx

Basically you wrap your Func<> type inside an Expression<> type and use its properties to parse it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜