Roslyn 静态分析

版权声明:http://blog.csdn.net/lindexi_gd 本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lindexi_gd/article/details/81772275

本文告诉大家如何使用 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#脚本(更新版) - 天方 - 博客园

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://lindexi.gitee.io/ 欢迎大家访问,里面有很多新的博客。只有在我看到博客写成熟之后才会放在csdn或博客园,但是一旦发布了就不再更新

如果在博客看到有任何不懂的,欢迎交流,我搭建了 dotnet 职业技术学院 欢迎大家加入

知识共享许可协议
本作品采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可。欢迎转载、使用、重新发布,但务必保留文章署名林德熙(包含链接:http://blog.csdn.net/lindexi_gd ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。如有任何疑问,请与我联系

猜你喜欢

转载自blog.csdn.net/lindexi_gd/article/details/81772275
今日推荐