繁体   English   中英

在 .netstandard 2.0 上迁移后无法编译简单的动态代码(CodeDom 抛出 System.PlatformNotSupportedException)

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

尝试编译此代码示例:

var c = new CSharpCodeProvider();
var cp = new CompilerParameters();
var className = $"CodeEvaler_{Guid.NewGuid().ToString("N")}";
// doesn't work with or without netstandard reference
var netstandard = Assembly.Load("netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51");
cp.ReferencedAssemblies.Add(netstandard.Location);
cp.CompilerOptions = "/t:library";
cp.GenerateInMemory = true;

var sb = new StringBuilder("");

sb.Append("namespace Jobs.Dynamic{ \n");
sb.Append($"public class {className} {{\n");
sb.Append($"public object RunSnippetCode()\n{{\n");
sb.Append("\nreturn null;\n");
sb.Append("\n}\n");
sb.Append("}");
sb.Append("}");

CompilerResults cr = c.CompileAssemblyFromSource(cp, sb.ToString());

在迁移到 .netstandard 2.0 之前一切正常

必须生成一个简单的类,如果只需复制代码并在 Visual Studio 中运行它,它就可以工作。 具有一种返回 null 的方法的类。 现在 CompileAssemblyFromSource 方法抛出

System.PlatformNotSupportedException:此平台不支持操作。 在 Microsoft.CSharp.CSharpCodeGenerator.FromFileBatch(CompilerParameters options, String[] fileNames) 在 Microsoft.CSharp.CSharpCodeGenerator.System.CodeDom.Compiler.ICodeCompiler.CompileAssemblyFromSourceBatch(CompilerParameters options, String[] sources) 在 CnetContent.Jobs.DynamicCode.. CnetContent.Jobs.Core.JobBase.EvalRunCondition(String& error) 上的ctor(IEnumerable 1 referencedAssemblies, IEnumerable 1 usings, String methodArgs, String codeSnippet)

我更新了 System.CodeDom 并且这个库支持 .netstandard 2.0,但是这个代码仍然不起作用。 找不到任何有类似问题的案例。 有什么想法吗? 提前谢谢你!

我在使用 .NetCore 2 时遇到了同样的问题,但使用了更大的 CodeDOM 项目。 我现在正在构建的解决方案是从 CodeDom 生成源代码,然后将其传递给 Roslyn。 (正如评论中提到的 Roslyn,但只发布了 .NET 框架解决方案)

这是如何使用 Roslyn 的一个很好的例子 - 只需添加

Microsoft.CodeAnalysis.CSharp NuGet 包和System.Runtime.Loader NuGet 包

然后使用这里的代码(或者只是按照示例): https : //github.com/joelmartinez/dotnet-core-roslyn-sample/blob/master/Program.cs

就我而言,我正在将一个项目从.NET Framework 4.7.2迁移到.NET Standard 2.0 在这个项目中,我有使用CSharpCodeProvider在运行时生成程序集的代码。 可以编译项目,但在运行时我的代码在从 Dom 生成程序集时抛出异常。 我收到此错误:

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=cc7b13ffcd2ddd51'.

因此,程序集不是在运行时创建的。

为了解决这个问题,我为编译器添加了.netstandard作为这样的引用程序集:

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

这对我有用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM