????????????????????????±???????????????????С???????????????????????????????????? VS2012 ???? .NET 4.5 ?????????????????÷???????????μ???????????????????????????ò??????á?

?????????????????????

public class MyMath
{
public int Add(int a?? int b)
{
return a + b??
}
}

?????????????????

?????????????????????????

????1. dynamic ????

????.NET 4 ?????? dynamic ???????????????·???????? MyMath.Add ?????????????

dynamic math = new MyMath()??
int result = math.Add(1?? 2)??

???????????Ч???????????????????????????????

??????????????? dynamic ???? .NET ?????????????????????п?????顣????????? dynamic ???? public ??????????????????????????internal ??????????????

????2. Expression Tree ???????

????Expression Tree ?? .NET 3.5 ????????????????????? lambda ??????? Expression Tree??

var math = new MyMath()??
Expression<Func<int?? int?? int>> add = (a?? b) => math.Add(a?? b)??

??????????????????????????????????????????????????

var add = typeof(MyMath).GetMethod("Add")??
var math = Expression.Parameter(typeof(MyMath))??
var a = Expression.Parameter(typeof(int)?? "a")??
var b = Expression.Parameter(typeof(int)?? "b")??
var body = Expression.Call(myMath?? add?? a?? b)??
var lambda = Expression.Lambda<Func<MyMath?? int?? int?? int>>(body?? math?? a?? b)??

?????????????????? Tree ????????

???????????????????????????????? Compile ????????????????У????′???? 3 ?У?

var math = new MyMath()??
Expression<Func<int?? int?? int>> addExpTree = (a?? b) => math.Add(a?? b)??  // ExressionTree
Func<int?? int?? int> add = addExpTree.Compile()??                         //  ????????
var result = add(1?? 2)??                                                 // ????????3

?????? dynamic ???÷??????Expression Tree ?????????з???????? .NET ?????????????????????п?????飬?????????г????

????3. ??????????

????????????????????????? DynamicMethod??.NET 2.0 ????????

??????? DynamicMethod ???????????????????????????????????????Щ??????

??????? MyMath.Add ????????????????????????Щ??

var addMethod = typeof(MyMath).GetMethod("Add")??
var dynamicMethod = new DynamicMethod(""?? typeof(int)?? new[] { typeof(MyMath)?? typeof(int)?? typeof(int) })??
//
var il = dynamicMethod.GetILGenerator()??
il.Emit(OpCodes.Ldarg_0)??
il.Emit(OpCodes.Ldarg_1)??
il.Emit(OpCodes.Ldarg_2)??
il.Emit(OpCodes.Callvirt?? addMethod)??
il.Emit(OpCodes.Ret)??
//
var add = (Func<MyMath?? int?? int?? int>)dynamicMethod.CreateDelegate(typeof(Func<MyMath?? int?? int?? int>))??
//
var math = new MyMath()??
var result = add(math?? 1?? 2)??

??????? 5 ??????ü??? IL ????????????

?????? 5 ?У?OpCodes.Ldarg_0 ???????? 0 ?????????????????Ldarg_1??Ldarg_2 ????????

?????? 6 ?У?OpCodes.Callvirt ???????????????????????????????????????????????

?????? 9 ?У?OpCodes.Ret ??????????????????????????????????????÷??????????????????÷???????????

???????????????????????????ζ??Ч?????????????????????????????? JIT ??????飬???? private ????????? DynamicMethod ???????DynamicMethod ?????? (String?? Type?? Type[]?? Boolean)????