如何在运行时编译c#-6.0+代码?

How to compile c#-6.0+ code at runtime?

我正在尝试在运行时编译代码并在其中创建 类 之一的实例,但在使用字符串插值等 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 '$'

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

有关详细信息,请参阅

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