2018-8-29-Roslyn-静态分析

title author date CreateTime categories
Roslyn 静态分析
lindexi
2018-08-29 09:10:19 +0800
2018-03-13 14:28:34 +0800
Roslyn MSBuild 编译器

本文告诉大家如何使用 Roslyn 分析代码。

首先创建一个项目,项目使用.net Framework 4.6.2 ,控制台项目。然后需要安装一些需要的库

Nuget 安装

打开 Nuget 安装下面两个库

  • Microsoft.CodeAnalysis.CSharp

  • Microsoft.CodeAnalysis.CSharp.Workspaces

  • Newtonsoft.Json

使用

下面来写简单的代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TrrluujHlcdyqa
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("hellow");
        }
    }

    class Foo
    {
        public string KiqHns { get; set; }
    }
}

对上面的代码分析

首先需要把上面的代码放在字符串

然后创建分析代码,读取代码。

   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 (classnode != null && !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)
        {
            string str = @"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TrrluujHlcdyqa
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(""hellow"");
        }
    }

    class Foo
    {
        public string KiqHns { get; set; }
    }
}";

            var tree = CSharpSyntaxTree.ParseText(str);

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

        }
    }

这时输出{"Foo":["KiqHns"]}

上面的代码从 https://stackoverflow.com/a/22881532/6116637 学的

更多关于 Roslyn 请看 手把手教你写 Roslyn 修改编译

参见:

通过Roslyn构建自己的C#脚本(更新版) - 天方 - 博客园

专栏:Roslyn 入门 - CSDN博客

Getting Started with Roslyn Analyzers

代码分析 - 借助与 NuGet 集成的 Roslyn 代码分析来生成和部署库

roslyn-analyzers/ReadMe.md at master · dotnet/roslyn-analyzers

In-memory C# compilation and .dll generation using Roslyn

原文地址:https://www.cnblogs.com/lindexi/p/12085511.html