zoukankan      html  css  js  c++  java
  • 使用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导入,再次运行就不会报错。

  • 相关阅读:
    Redis之通用的key操作命令
    Redis常用命令之操作Set(集合)
    Redis常用命令之操作SortedSet(有序集合)
    Redis常用命令之操作List类型
    Winform中实现监控CPU内存使用率(附代码下载)
    Ubuntu安装配置mongodb
    修改Ubuntu国内镜像
    redis安装和配置
    爬虫(十六):scrapy爬取知乎用户信息
    爬虫(十五):scrapy中的settings详解
  • 原文地址:https://www.cnblogs.com/smartisn/p/15042870.html
Copyright © 2011-2022 走看看