我尝试使用 Roslyn 编译器在运行时编译一些源代码。为此我做到了
public static void compile()
{
SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(code);
}
当然这段代码没有做太多事情,但它通过问题表明:
每当我尝试执行编译方法时,我都会遇到异常
Could not load file or assembly 'Microsoft.CodeAnalysis, Version=4.9.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'
也许这是版本问题?我真的被困在这里了。 我正在使用VS2019和.Net5(我认为这是最新的.Net VS2019支持)
通过 NuGetPackage Manager 我将其包含在我的项目中:
项目文件看起来像这样
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.Common" Version="4.9.2" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.9.2" />
</ItemGroup>
构建时我收到警告:
1>C:\Users\werber\.nuget\packages\system.text.encoding.codepages\8.0.0\buildTransitive\netcoreapp2.0\System.Text.Encoding.CodePages.targets(4,5): warning : System.Text.Encoding.CodePages 8.0.0 doesn't support net5.0 and has not been tested with it. Consider upgrading your TargetFramework to net6.0 or later. You may also set <SuppressTfmSupportBuildWarnings>true</SuppressTfmSupportBuildWarnings> in the project file to ignore this warning and attempt to run in this unsupported configuration at your own risk.
1>C:\Users\werber\.nuget\packages\system.collections.immutable\8.0.0\buildTransitive\netcoreapp2.0\System.Collections.Immutable.targets(4,5): warning : System.Collections.Immutable 8.0.0 doesn't support net5.0 and has not been tested with it. Consider upgrading your TargetFramework to net6.0 or later. You may also set <SuppressTfmSupportBuildWarnings>true</SuppressTfmSupportBuildWarnings> in the project file to ignore this warning and attempt to run in this unsupported configuration at your own risk.
1>C:\Users\werber\.nuget\packages\system.reflection.metadata\8.0.0\buildTransitive\netcoreapp2.0\System.Reflection.Metadata.targets(4,5): warning : System.Reflection.Metadata 8.0.0 doesn't support net5.0 and has not been tested with it. Consider upgrading your TargetFramework to net6.0 or later. You may also set <SuppressTfmSupportBuildWarnings>true</SuppressTfmSupportBuildWarnings> in the project file to ignore this warning and attempt to run in this unsupported configuration at your own risk.
该怎么办以及如何解决这个问题?
Roslyn 4.x 仅在 Visual Studio 2022 中支持。VS 之间的映射请参见 https://learn.microsoft.com/en-us/visualstudio/extensibility/roslyn-version-support?view=vs-2022和罗斯林包