2017-06-16 142 views
0

我想在运行时编译代码并创建其中一个类的实例,但在使用c#6+功能(如字符串插值)时遇到一些错误。下面是我使用的编译代码:如何在运行时编译c#-6.0 +代码?

 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 '$'

+0

如何编译此代码?用哪个编译器版本?您需要一个理解并可以解析C#6.0语法的编译器 – Steve

+0

您正在使用哪种Visual Studio版本?要获得完整的C#6.0支持,您需要VS2015或VS2017。 – Atesh052

+0

@ Atesh052我正在使用VS2017。 –

回答