Cannot compile simple dynamic code after migration on .netstandard 2.0 (CodeDom throws System.PlatformNotSupportedException)

前端 未结 2 713
Happy的楠姐
Happy的楠姐 2021-02-09 01:38

Trying to compile this sample of code:

var c = new CSharpCodeProvider();
var cp = new CompilerParameters();
var className = $\"CodeEvaler_{Guid.NewGuid().ToStrin         


        
相关标签:
2条回答
  • 2021-02-09 01:54

    I had the same problem with .NetCore 2, but with a bigger CodeDOM project. My solution I am right now building is generating the source from CodeDom and then passing it to Roslyn. (As Roslyn was mentioned in a comment, but only a .NET Framwork solution was posted)

    Here is a good example how to use Roslyn - just add the

    Microsoft.CodeAnalysis.CSharp NuGet package and System.Runtime.Loader NuGet package

    and then use the code here (Or just follow the example): https://github.com/joelmartinez/dotnet-core-roslyn-sample/blob/master/Program.cs

    0 讨论(0)
  • 2021-02-09 01:58

    In my case I was migrating a project from .NET Framework 4.7.2 to .NET Standard 2.0. In this project I have code to generate an assembly during runtime by using CSharpCodeProvider. Could compile the project but then during runtime my code threw an exception when generating an assembly from Dom. I got this error:

    CS0012: The type 'System.Object' is defined in an assembly that is not referenced. You must add a reference to assembly 'netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ffffd51'.
    

    As a consequence the assembly was not created during runtime.

    In order to fix that I have added .netstandard for the compiler as a referenced assembly like that:

    var compilerParameters = new CompilerParameters();
    var netstandard = Assembly.Load("netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ffffd51");
    compilerParameters.ReferencedAssemblies.Add(netstandard.Location);
    

    That did the trick for me.

    0 讨论(0)
提交回复
热议问题