使用开源发布的“roslyn"读取代码文件并生成新的代码文件 [英] Using the open source released "roslyn" to read code file and generate new code files

查看:53
本文介绍了使用开源发布的“roslyn"读取代码文件并生成新的代码文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从哪里开始?

在我目前的解决方案中,我有这样的模型:

in my current solution I have models like this:

public class MyAwesomeModel
{
 ....
}

我想拿 roslyn 代码项目来解析源文件并遍历语法树以生成新的代码文件.将这些源文件添加到 C# 项目文件中,以便在 Visual Studio 中再次导入我的解决方案.

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.

我从哪里开始.克隆 roslyn,然后编写一个引用所有 roslyn 的控制台应用程序,然后开始深入研究 roslyn 以了解如何或是否有任何博客、文档显示此类内容.

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.

推荐答案

做起来有点容易.

创建控制台应用程序并添加对 Microsoft 的引用.CodeAnalysis.CSharp 在您的项目中.

Create a console app and add reference to Microsoft.CodeAnalysis.CSharp in your project.

这是访问源文本中所有属性的程序:

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

using System;
using System.Collections.Generic;
using System.Text.Json;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;

class ModelCollector : CSharpSyntaxWalker
{
    public Dictionary<string, List<string>> Models { get; } = 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()
    {
        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(JsonSerializer.Serialize(modelCollector.Models));
    }
}

这篇关于使用开源发布的“roslyn"读取代码文件并生成新的代码文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆