Using the open source released “roslyn” to read code file and generate new code files

℡╲_俬逩灬. 提交于 2019-12-20 13:57:13

问题


Where do I start?

in my current solution I have models like this:

public class MyAwesomeModel
{
 ....
}

I want to take the roslyn code project to parse the source files and go over the syntax trees to generate new code files. Take those source files and add them to a c# project file to import in my solution again in visual studio.

Where do I start. Cloning roslyn and just write a console app that reference all of roslyn and start digging into roslyn to find out how, or is there any blogs,documentatino that shows something like this.


回答1:


It was somewhat easy to do.

Create a console app and reference:

  <package id="Microsoft.CodeAnalysis.CSharp" version="0.6.4033103-beta" targetFramework="net45" />

and here is the program that visited all properties in a source text:

 class ModelCollector : CSharpSyntaxWalker
    {
        public readonly Dictionary<string, List<string>> models = new Dictionary<string, List<string>>();
        public override void VisitPropertyDeclaration(PropertyDeclarationSyntax node)
        {
            var classnode = node.Parent as ClassDeclarationSyntax;
            if (!models.ContainsKey(classnode.Identifier.ValueText))
                models.Add(classnode.Identifier.ValueText, new List<string>());

            models[classnode.Identifier.ValueText].Add(node.Identifier.ValueText);
        }

    } 


    class Program
    {
        static void Main(string[] args)
        {

            var code =
@"              using System; 
                using System.Collections.Generic; 
                using System.Linq; 
                using System.Text; 

                namespace HelloWorld 
                { 
                    public class MyAwesomeModel
                    {
                        public string MyProperty {get;set;}
                        public int MyProperty1 {get;set;}
                    }

                }";

            var tree = CSharpSyntaxTree.ParseText(code);

            var root = (CompilationUnitSyntax)tree.GetRoot();
            var modelCollector = new ModelCollector();
            modelCollector.Visit(root);
            Console.WriteLine(JsonConvert.SerializeObject(modelCollector.models));


        }
    }


来源:https://stackoverflow.com/questions/22879776/using-the-open-source-released-roslyn-to-read-code-file-and-generate-new-code

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