我从哪里开始?
在我当前的解决方案中,我有这样的模型:
public class MyAwesomeModel
{
....
}
我想利用roslyn代码项目来解析源文件并遍历语法树以生成新的代码文件。获取这些源文件并将它们添加到 c# 项目文件中,以便在 visual studio 中再次导入我的解决方案。
我从哪里开始。克隆 roslyn 并编写一个引用所有 roslyn 的控制台应用程序,然后开始深入研究 roslyn 以了解如何,或者是否有任何博客、文档显示类似这样的内容。
最佳答案
这有点容易做到。
创建控制台应用程序并添加对 Microsoft.CodeAnalysis.CSharp 的引用在你的项目中。
这是访问源文本中所有属性的程序:
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));
}
}
关于c# - 使用开源发布的 "roslyn"读取代码文件并生成新的代码文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22879776/