简体   繁体   中英

Properties, methods, lambda expressions used in the code

I have a code:

using System.Linq.Expressions;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Expression<del> myET = x => x.Age; //for example in ASP.NET MVC forms
            Person.Name = "vitia"
            Person.Move();

        }
    }
}

I would like to know how to use Roslyn.NET can "pull" and write to the console all the methods, properties, and lambda used in the code. Now I'm sitting on this for a few good hours and I can not think of anything. I tried to use the MemberAccesExpressionSyntax here but I do not really it came out. Can you show some examples of doing something like that? With this code, the screen would put the console:

x.Age Name Move

This is the sort of query you are looking for:

var expressionNodes = syntaxTree.
    GetRoot().
    DescendantNodes().Where(n => n.Kind == SyntaxKind.[YourSyntaxKind]);

Below is the full sample of code. You ought to be able to paste it into your C# console app.

I've pulled out:

  • Parentesised Lambdas
  • Simple Lambdas
  • Methods

I'll leave as an excercise for yourself to pull out the rest of what you need.

private static void StackOverflowTest()
{
    var syntaxTree = SyntaxTree.ParseText(@"
    using System.Linq.Expressions;

    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                Expression<del> myET = x => x.Age; //for example in ASP.NET MVC forms
                Person.Name = ""vitia""
                Person.Move();

            }
        }
    }");

    EmitStatement(syntaxTree, SyntaxKind.ParenthesizedLambdaExpression);
    EmitStatement(syntaxTree, SyntaxKind.SimpleLambdaExpression);
    EmitStatement(syntaxTree, SyntaxKind.MethodDeclaration);
}

private static void EmitStatement(SyntaxTree syntaxTree, SyntaxKind sk)
{
    var expressionNodes = syntaxTree.
        GetRoot().
        DescendantNodes().Where(n => n.Kind == sk);

    foreach (var expressionNode in expressionNodes)
    {
        Console.WriteLine(expressionNode.ToString());
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM