2012-04-03 49 views
1

我正在使用c#創建一個自定義代碼生成器...此生成器現在僅從數據庫的表中創建商業實體。但現在我想要的是創建一個包含此類的項目並在其創建後......從項目生成dll。創建類並從c#編譯它#

有沒有辦法做這份工作?

+2

如果你需要創建一個Visual Studio項目,可以扭轉很容易工程項目文件。如果沒有,只需使用指定您生成的文件的命令行調用csc.exe即可。它看起來相當簡單,所以我不明白你所困擾的是什麼,如果你足夠先進的話可以編寫一個從數據庫模式生成C#代碼的程序。 – phoog 2012-04-03 22:33:11

+0

你的意思是你有C#方法,你想創建一個* .dll文件,別人可以添加到項目中並調用這些方法? – JMK 2012-04-03 22:34:56

+0

@JMK我有一個方法可以生成* .cs文件。現在我想在C#項目中對這些文件進行分組,並從該項目中創建一個* .dll – jcvegan 2012-04-03 22:55:56

回答

2

你可以使用CSharpCodeProvider編譯代碼的DLL,像這樣(的地方在互聯網上找到):

public static bool CompileCSharpCode(String sourceFile, String outFile) 
     { 
      // Obtain an ICodeCompiler from a CodeDomProvider class. 
      CSharpCodeProvider provider = new CSharpCodeProvider(); 
      ICodeCompiler compiler = provider.CreateCompiler(); // Build the parameters for source compilation. 
      CompilerParameters cp = new CompilerParameters(); // Add an assembly reference. 
      cp.ReferencedAssemblies.Add("System.dll"); // Generate an class library instead of // a executable. 
      cp.GenerateExecutable = false; // Set the assembly file name to generate. 
      cp.OutputAssembly = outFile; // Save the assembly as a physical file. 
      cp.GenerateInMemory = false; // Invoke compilation. 
      CompilerResults cr = compiler.CompileAssemblyFromFile(cp, sourceFile); 
      if (cr.Errors.Count > 0) 
      { // Display compilation errors. 
       Console.WriteLine("Errors building {0} into {1}", sourceFile, cr.PathToAssembly); 
       foreach (CompilerError ce in cr.Errors) 
       { 
        Console.WriteLine(" {0}", ce.ToString()); 
        Console.WriteLine(); 
       } 
      } 
      else 
      { 
       Console.WriteLine("Source {0} built into {1} successfully.", sourceFile, cr.PathToAssembly); 
      } // Return the results of compilation. 
      if (cr.Errors.Count > 0) { return false; } else { return true; } 
     } 
1

您可以使用反射並使用emit或使用Process類來調用c#編譯器,一旦生成了所有內容。