2017-06-16 80 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。 –

回答