extending c# syntax with roslyn

♀尐吖头ヾ 提交于 2019-12-10 14:12:18

问题


I'm trying to implement a "return if"/"return value if" without an else case, since I only want to return or return a value if a condition is valid.

I know, there is the if (condition) return; or if (condition) return value; but I want to have the code a bit cleaner AND it would be nice to have that syntax since it is more readable.

I heard with roslyn this is possible and read the question with its answeres here: Is there a way to implement custom language features in C#? but I have no clue how to implement it.

So the code would be something like this:

public class Testclass
{
    public static void Main(String[] args)
    {
        Testclass t = new Testclass();
        t.TestMyClassWithVoid();
        bool success = t.TestMyClassWithInt(3) == 3;
        bool fail = t.TestMyClassWithInt(2) == 2;
    }

    public void TestMyClassWithVoid()
    {
        int value = GetValueFromSomeWhere();
        return if value == 3;

        DoSomeOtherStuffSinceValueIsNotThree();
    }

    public int TestMyClassWithInt(int value)
    {
        return value if value == 3;

        DoSomeOtherStuffSinceValueIsNotThree();
        return -1;
    }
}

any idea how I could solve this? I started trying with the Roslyn.Compilers.CSharp-namespace but I have no clue how to start implementing.


回答1:


If you can generate the correct IL for this, this should be work. Because this is not a new CLR capability you don't need do anything with dot net core, just Roslyn.

To do that you have two options,

One is to leave Roslyn as is and rewrite your new syntax to the correspond C# syntax and then compile as regular.

Second option, because Roslyn is an open source, is to add the ability to compile you new syntax to your own Roslyn and compile your code with it.




回答2:


Here is an alternative suggestion that may work for someone who is looking for extension points into roslyn. It can even be provided as a nuget package! Create an analyser and a code fix provider for your syntax.

Essentially what you would get is a red squiggly line under any syntax of your choosing, with a auto-fix hint which would let you transform it into the regular C# equivalent.

It could also be used for validating the usage of your library, checking that the right attributes are in the right locations, detect common code smells, etc.

Read up more on code analysers at this post: https://msdn.microsoft.com/en-us/magazine/dn879356.aspx

A quick summary of that link (but by no means a replacement):

  • Install VS SDK, Roslyn SDK, Compiler Platform SDK
  • Create new project: Analyzer with Code Fix (NuGet + VSIX) template.
  • There will be 3 samples on how to create an analyser / code fix provider
  • Set the VSIX project as the startup project and run


来源:https://stackoverflow.com/questions/38786359/extending-c-sharp-syntax-with-roslyn

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!