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

前端 未结 2 714
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: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.

提交回复
热议问题