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

时间:2017-06-16 11:46:06

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

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

1 个答案:

答案 0 :(得分:1)

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

请参阅https://stackoverflow.com/a/40311406/34092了解详情

非常感谢帮助我解决这个问题的@mjwillis。