简体   繁体   中英

Roslyn fluent syntax to create expression tree for multiline lambda

I am writing a Roslyn-based custom tool that tries to eradicate CS0834 by rewriting given multi-line lambdas into Expression trees at build time.

Edit : At this time, I am only targeting anonymous multiline lambdas.

For example:

    // Will produce CS0834 if Bar takes Expression<Action<...>>
    Foo.Bar((int x) => { ... });

to

    Foo.Bar(Expression.Lambda<Action<int>>(
        Expression.Block(
            ...
            ),
        Expression.Parameter(typeof(int))));

So that will compile correctly. While I can figure out the Expression.(blah) syntax required to convert the given code, doing it using Roslyn is another matter altogether. Perhaps I just don't know the Roslyn Syntax.(blah) API well enough to translate this raw lambda

    (int index, float[] a, float[] b) =>
    {
        var sum = 0f;
        for (int i = 0; i < index; i++)
            sum += a[i];

        b[index] = sum;
    });

Could someone help me write the Roslyn Syntax.(blah) syntax that will generate an expression tree that looks like the one below?

    Expression<Action<int, float[], float[]>> action = 
        Expression.Lambda(
            Expression.Block(
                Expression.Assign(sumParameter, Expression.Constant(0)),
                Expression.Loop(...) // The for loop here
                )
            );

Once I have a starting point - I ought to be able to figure out or at least get started translating simple cases in this project.

Many thanks, your help is much appreciated.

We have a tool called Quoter that will generate Syntax.* API calls for any C# program .

You can view it live at roslynquoter.azurewebsites.net .

If you figure out the logic to generate the Expression.* calls, you can easily generate code that generates it.

Update: the tool is now open-source! https://github.com/KirillOsenkov/RoslynQuoter

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