使用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:\Developments\Open\MSTestEnhancer\MSTest.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导入,再次运行就不会报错。

posted @ 2021-07-22 10:16  博二爷  阅读(135)  评论(0编辑  收藏  举报