• 使用Roslyn 使用MSBuild进行编译,项目不报错,但是运行显示ReflectionTypeLoadException,解决方案


    案例代码(来源:Roslyn 入门:使用 Roslyn 静态分析现有项目中的代码 - walterlv - 博客园 (cnblogs.com)

     1 using System;
     2 using System.IO;
     3 using System.Linq;
     4 using System.Threading.Tasks;
     5 using Microsoft.CodeAnalysis;
     6 using Microsoft.CodeAnalysis.CSharp;
     7 using Microsoft.CodeAnalysis.CSharp.Syntax;
     8 using Microsoft.CodeAnalysis.MSBuild;
     9 
    10 namespace Walterlv.Demo.Roslyn
    11 {
    12     class Program
    13     {
    14         static void Main(string[] args)
    15         {
    16             RunAsync().Wait();
    17         }
    18 
    19         private static async Task RunAsync()
    20         {
    21             var solution = await MSBuildWorkspace.Create().OpenSolutionAsync(
    22                 @"D:DevelopmentsOpenMSTestEnhancerMSTest.Extensions.sln");
    23             var project = solution.Projects.First(x => x.Name == "MSTest.Extensions");
    24             var document = project.Documents.First(x =>
    25                 x.Name.Equals("ContractTestContext.cs", StringComparison.InvariantCultureIgnoreCase));
    26 
    27             var tree = await document.GetSyntaxTreeAsync();
    28             var syntax = tree.GetCompilationUnitRoot();
    29 
    30             var visitor = new TypeParameterVisitor();
    31             var node = visitor.Visit(syntax);
    32 
    33             var text = node.GetText();
    34             File.WriteAllText(document.FilePath, text.ToString());
    35         }
    36     }
    37 
    38     class TypeParameterVisitor : CSharpSyntaxRewriter
    39     {
    40         public override SyntaxNode VisitTypeParameterList(TypeParameterListSyntax node)
    41         {
    42             var syntaxList = new SeparatedSyntaxList<TypeParameterSyntax>();
    43             syntaxList = syntaxList.Add(SyntaxFactory.TypeParameter("TParameter"));
    44 
    45             var lessThanToken = this.VisitToken(node.LessThanToken);
    46             var greaterThanToken = this.VisitToken(node.GreaterThanToken);
    47             return node.Update(lessThanToken, syntaxList, greaterThanToken);
    48         }
    49     }
    50 }

    但是运行出错:

    System.Reflection.ReflectionTypeLoadException:

    解决方案(亲测有效):

    只需要在NuGet中在安装上Microsoft.Build,Microsoft.Build.Utilities.Core,不用using导入,再次运行就不会报错。

  • 相关阅读:
    开源项目
    测试面试话题8:测试人员如何让开发少写bug?
    其他
    接口平台
    001接口概念
    python3PIL模块实现图片加文字/小图片水印
    python3实现url编码/解码
    python3实现读取Excel进行接口自动化测试
    常用正则表达式
    Python3实现简单的接口性能测试
  • 原文地址:https://www.cnblogs.com/smartisn/p/15042870.html
Copyright © 2020-2023  润新知