【问题标题】:How to compile c#-6.0+ code at runtime?如何在运行时编译 c#-6.0+ 代码?
【发布时间】:2017-06-16 23:36:48
【问题描述】:

我正在尝试在运行时编译代码并创建其中一个类的实例,但是在使用字符串插值等 c# 6+ 功能时出现一些错误。这是我用来编译的代码:

        using (var cs = new CSharpCodeProvider())
        {
            var assembly = typeof(MyType).Assembly;
            var cp = new CompilerParameters()
            {
                GenerateInMemory = false,
                GenerateExecutable = false,
                IncludeDebugInformation = true,
            };

            if (Environment.OSVersion.Platform.ToString() != "Unix") cp.TempFiles = new TempFileCollection(Environment.GetEnvironmentVariable("TEMP"), true);
            else cp.TempFiles.KeepFiles = true;
            cp.ReferencedAssemblies.Add("System.dll");
            cp.ReferencedAssemblies.Add("System.Core.dll");
            cp.ReferencedAssemblies.Add(assembly.Location);
            CompilerResults cr;

            if (Directory.Exists(path))
            {
                string[] files = Directory.GetFiles(path, "*.cs", SearchOption.AllDirectories);
                cr = cs.CompileAssemblyFromFile(cp, files);
            }
            else cr = cs.CompileAssemblyFromFile(cp, new string[] { path });


            if (cr.Errors.HasErrors)
                throw new Exception("Compliation failed, check your code.");


            var types = cr.CompiledAssembly.GetTypes();
            var myType = types.Where(x => x.GetInterfaces().Contains(typeof(MyType))).FirstOrDefault();
            if (myType == null)
                throw new TypeLoadException("Could not find MyType class");

            return (MyType)cr.CompiledAssembly.CreateInstance(myType.FullName);

        }

现在,如果我尝试编译使用以下代码的代码:

string name = $"My name is {name}";

我得到了这个例外: Unexpected character '$'

【问题讨论】:

  • 如何编译这段代码?使用哪个编译器版本?您需要一个能够理解并能够解析 C# 6.0 语法的编译器
  • 您使用的是哪个 Visual Studio 版本?要获得完整的 C# 6.0 支持,您需要 VS2015 或 VS2017。
  • @Atesh052 我正在使用 VS2017。
  • @mjwills 我该如何检查?
  • 那些看起来像正确的版本。 stackoverflow.com/a/40311406/34092 有帮助吗?

标签: c# compilation c#-6.0 runtime-compilation


【解决方案1】:

解决该问题的方法是使用Microsoft.CodeDom.Providers.DotNetCompilerPlatform。而且我还必须将using Microsoft.CSharp 更改为Microsoft.CodeDom.Providers.DotNetCompilerPlatform

查看https://stackoverflow.com/a/40311406/34092了解更多信息

非常感谢@mjwillis 帮助我找到了这个解决方案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多