首页 > 解决方案 > 该平台不支持操作

问题描述

我有一个简单的项目.NetFramework 3.5 Class library

c# dynamic code我在项目中的runtime(with CodeDom)处编译并运行,.NetFramework并从项目中调用Asp.NetCore 2.0

当我从项目BuildAssembly中调用类中的方法时,遇到此错误:(CodeDom throws)CommonAsp.NetCore 2.0

"System.PlatformNotSupportedException":"此平台不支持操作。" 在 Microsoft.CSharp.CSharpCodeGenerator.FromFileBatch(CompilerParameters options, String[] fileNames) 在 Microsoft.CSharp.CSharpCodeGenerator.System.CodeDom.Compiler.ICodeCompiler.CompileAssemblyFromSourceBatch(CompilerParameters options, String[] sources)

以下代码:

.NetFrameWork 3.5:

public class Common
{
    public Assembly BuildAssembly(string code)
    {
        CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp");
        CompilerParameters compilerparams = new CompilerParameters();
        compilerparams.GenerateExecutable = false;//Generate an executable instead of a class library
        compilerparams.GenerateInMemory = false; //Save the assembly as a physical file.

        compilerparams.ReferencedAssemblies.Add("mscorlib.dll");
        compilerparams.ReferencedAssemblies.Add("System.dll");
        compilerparams.ReferencedAssemblies.Add("System.Data.dll");
        compilerparams.ReferencedAssemblies.Add("System.Xml.dll");

        CompilerResults results = codeProvider.CompileAssemblyFromSource(compilerparams, code);
        if (results.Errors.HasErrors)
        {
            StringBuilder errors = new StringBuilder("Compiler Errors :\r\n");
            foreach (CompilerError error in results.Errors)
            {
                errors.AppendFormat("Line {0},{1}\t: {2}\n",
                        error.Line, error.Column, error.ErrorText);
            }
            throw new Exception(errors.ToString());
        }
        else
        {
            return results.CompiledAssembly;
        }
    }
}

Asp.NetCore 2.0:

public IActionResult Test()
{
    string code = @"
using System;
using System.Text;
using System.Data;
using System.Reflection;
using System.ComponentModel;

namespace testNameSpace
{
    public class DynamicClass
    {
         public string Test() {     return ""Hello world""; }
    }
}";
    var res = new Common().BuildAssembly(code);
    return Json("ok");
}

我在网上搜索并根据此链接安装了Microsoft.CodeAnalysis.CSharpnuget 包并进行了测试,但它不起作用。

我不能用这种方式编译简单的代码。

如何解决此错误?

标签: c#.net-coreasp.net-core-2.0

解决方案


推荐阅读