Emit Vs CodeDom

來源:互聯網
上載者:User

Emit 和 CodeDom 都是用來動態建立類型,並利用反射執行的東東~~~~ 這兩個都是 .NET Framework 中比較有深度的內容。

有關 CodeDom,雨痕已經寫過好幾篇了,此處不再詳述。CodeDom 利用 C#/VB.NET 等編譯引擎進行動態編譯,而 Emit 則直接使用 IL,從編程方便的角度來說 CodeDom 更方便一點。當然 CodeDom 要花費一定的編譯時間,而一旦載入則和 Emit 或靜態編譯器集沒有什麼區別。Emit 被很多 AOP/ORM 組件所使用,除了 ILGenerator 外,和 CodeDom 的編程習慣很相似。接下來雨痕會寫幾篇 Emit 的使用文章。

好了,從經典的 "Hello, World!" 開始。我們本次的目標是用 Emit 重寫下面的類型,並完成動態調用。

 

代碼

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.CodeDom;
using System.Reflection;
using System.Reflection.Emit;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Globalization;

namespace ConsoleApplication5
{
/// <summary>
/// Emit 和 CodeDom 都是用來動態建立類型,並利用反射執行的東東~~~~
/// </summary>
class Program
{
static void Main(string[] args)
{
/*
//一,Emit 則直接使用 IL
//1. 定義動態程式集
AssemblyName assemblyName = new AssemblyName("Nettip.Assembly");
AssemblyBuilder assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);

//2. 定義動態模組
ModuleBuilder module = assembly.DefineDynamicModule("Nettip.QueryOrderConditon.Module");

//3. 定義類型
TypeBuilder type = module.DefineType("QueryOrderCondition", TypeAttributes.Class, typeof(object));

//4. 定義方法
MethodBuilder method = type.DefineMethod("Test", MethodAttributes.Public, CallingConventions.HasThis, null, null);

//5. 方法代碼
ILGenerator il = method.GetILGenerator();
il.Emit(OpCodes.Nop);
il.Emit(OpCodes.Ldstr, "Hello, World!");
il.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }));
il.Emit(OpCodes.Nop);
il.Emit(OpCodes.Ret);

//6. 執行
Type class1 = type.CreateType();
object o = Activator.CreateInstance(class1);
o.GetType().GetMethod("Test").Invoke(o, null);
*/
//二,CodeDom 利用 C#/VB.NET 等編譯引擎進行動態編譯

#region
// 1. 使用CodeDom建立源碼
//CodeCompileUnit cu = new CodeCompileUnit();
//CodeNamespace Samples = new CodeNamespace("Samples");
//cu.Namespaces.Add(Samples);
//Samples.Imports.Add(new CodeNamespaceImport("System"));
//CodeTypeDeclaration Class1 = new CodeTypeDeclaration("Class1");
//Samples.Types.Add(Class1);
//CodeEntryPointMethod Start = new CodeEntryPointMethod();
//CodeMethodInvokeExpression cs1 = new CodeMethodInvokeExpression(
// new CodeTypeReferenceExpression("System.Console"), "WriteLine",
// new CodePrimitiveExpression("Hello World!") );
//Start.Statements.Add(new CodeExpressionStatement(cs1));
//Class1.Members.Add(Start);

string code = @"
using System;
namespace Nettip
{
public class QueryOrderCondition

private string name;

public QueryOrderCondition(string name)
{
this.name = name;
}

public void Test()
{
Console.WriteLine(""{0} - {1}"", name, DateTime.Now);
}
}
}
";

#endregion
//1. 建立編譯器對象
CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");

//2. 設定編譯參數
CompilerParameters cp = new CompilerParameters();
cp.ReferencedAssemblies.Add("System.dll");
cp.GenerateInMemory = false;
cp.OutputAssembly = "Nettip.QueryOrderCondition.dll";

//3. 開始編譯
CompilerResults results = provider.CompileAssemblyFromSource(cp, code);
//3.1 顯示編譯資訊
if (results.Errors.Count == 0)
Console.WriteLine("\"{0}\" compiled ok!", results.CompiledAssembly.Location);
else
{
Console.WriteLine("Complie Error:");
foreach (CompilerError error in results.Errors)
Console.WriteLine(" {0}", error);
}

//4.執行
Type t = results.CompiledAssembly.GetType("Nettip.QueryOrderCondition");
object o = results.CompiledAssembly.CreateInstance("Nettip.QueryOrderCondition", false, BindingFlags.Default,
null, new object[] { "Tom" }, CultureInfo.CurrentCulture, null);
t.InvokeMember("Test", BindingFlags.Instance | BindingFlags.Public | BindingFlags.InvokeMethod,
null, o, null);
}
}
}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.