C#動態產生代碼和程式集

來源:互聯網
上載者:User

以下代碼動態產生cs檔案

編譯為Assembly 

之後可以使用AppDomain.Load 載入程式集,並建立類型

 public static  void Test()
{
//聲明代碼的部分
CodeCompileUnit compunit = new CodeCompileUnit();
CodeNamespace sample = new CodeNamespace("命名空間");
compunit.Namespaces.Add(sample);

//引用命名空間
sample.Imports.Add(new CodeNamespaceImport("System"));//匯入System命名空間
sample.Imports.Add(new CodeNamespaceImport("System.Linq"));//匯入System.Linq命名空間

//在命名空間下添加一個類
CodeTypeDeclaration wrapProxyClass = new CodeTypeDeclaration("類名");
//wrapProxyClass.BaseTypes.Add(baseType);// 如果需要的話 在這裡聲明繼承關係 (基類 , 介面)
wrapProxyClass.CustomAttributes.Add(new CodeAttributeDeclaration("Serializable"));//添加一個Attribute到class上
sample.Types.Add(wrapProxyClass);//把這個類添加到命名空間 ,待會兒才會編譯這個類

//為這個類添加一個無參建構函式 其實不添加也沒事的, 只是做個demo而已
CodeConstructor constructor = new CodeConstructor();
constructor.Attributes = MemberAttributes.Public;
wrapProxyClass.Members.Add(constructor);


//為這個類添加一個方法 public override int 方法名(string str);
System.CodeDom.CodeMemberMethod method = new CodeMemberMethod();
method.Name = "方法名";
method.Attributes = MemberAttributes.Override | MemberAttributes.Public;//聲明方法是公開 並且override的
method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string ), "str")); //這個方法添加一個輸入參數
method.ReturnType =new CodeTypeReference( typeof(int));//聲明傳回值的類型
method.Statements.Add(new CodeSnippetStatement(" return 1; ")); //方法體裡面很簡單 直接返回 一個1;



CSharpCodeProvider cprovider = new CSharpCodeProvider();

ICodeGenerator gen = cprovider.CreateGenerator();
StringBuilder fileContent = new StringBuilder();
using (StringWriter sw = new StringWriter(fileContent))
{
gen.GenerateCodeFromCompileUnit(compunit, sw, new CodeGeneratorOptions());//想把產生的程式碼儲存為cs檔案
}

ICodeCompiler compiler = cprovider.CreateCompiler();

//編譯參數
CompilerParameters cp = new CompilerParameters();
cp.ReferencedAssemblies.Add("System.dll");//剛才引用了命名空間 這裡是添加引用
cp.ReferencedAssemblies.Add("System.Core.dll");//剛才引用了命名空間 這裡是添加引用

cp.OutputAssembly = "輸出dll的位置";
cp.GenerateInMemory = false; //是否只在記憶體中產生
cp.IncludeDebugInformation = true;//包含偵錯符號 pdb檔案
cp.GenerateExecutable = false;//產生dll,不是exe
cp.WarningLevel = 4;
cp.TreatWarningsAsErrors = false;

string filePath = "產生cs檔案的儲存位置";
File.WriteAllText(filePath, fileContent.ToString());
CompilerResults cr = compiler.CompileAssemblyFromFile(cp, filePath); //儲存檔案再進行編譯 待會兒調試就比較方便了 ,可以直接斷點到剛才產生的檔案裡面
// CompilerResults cr = compiler.CompileAssemblyFromDom(cp, compunit); //這樣的產生 不用寫檔案 ,就是調試麻煩
String outputMessage = "";
foreach (var item in cr.Output)
{
outputMessage += item + Environment.NewLine;//調試的最終輸出資訊
}
if (cr.Errors.Count > 0)//有編譯錯誤就拋出異常
{
throw new Exception("error:" + Environment.NewLine + outputMessage);
}

}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.