public static void BuildGetMethod(EmitData td) { Type t = td.GetType(); PropertyInfo pi = t.GetProperty("Name"); if (pi != null) { MethodInfo getter = pi.GetGetMethod(); PropGet = (PropertyGetter <int>)Delegate.CreateDelegate(typeof(PropertyGetter <int>), td, getter); } }
public static void EmitDemo() { Console.Write("当前framework版本:" + Environment.Version.Major + "<br/>"); int max = 1000000; Console.Write("循环次数:" + max + "<br/>"); //基本方法 DateTime time = DateTime.Now; EmitData d = new EmitData(); for (int i = 0; i < max; i++) { d.Name = i; } TimeSpan ts = DateTime.Now - time; Console.Write("基本方法:" + ts.TotalMilliseconds + "<br/>"); //反射方法 Type type = d.GetType(); PropertyInfo pi = type.GetProperty("Name"); time = DateTime.Now; for (int i = 0; i < max; i++) { pi.SetValue(d, i, null); } ts = DateTime.Now - time; Console.Write("反射方法:" + ts.TotalMilliseconds + "<br/>"); //dynamic动态类型方法 dynamic dobj = Activator.CreateInstance <EmitData>(); time = DateTime.Now; for (int i = 0; i < max; i++) { dobj.Name = i; } ts = DateTime.Now - time; Console.Write("dynamic动态类型方法:" + ts.TotalMilliseconds + "<br/>"); //泛型委托赋值方法 d.Name = -1; BuildSetMethod(d); time = DateTime.Now; for (int i = 0; i < max; i++) { PropSet(i); } ts = DateTime.Now - time; Console.Write("泛型委托赋值方法:" + ts.TotalMilliseconds + "<br/>"); Console.Write("v:" + d.Name + "<br/>"); //泛型委托取值方法 d.Name = -1; BuildGetMethod(d); time = DateTime.Now; for (int i = 0; i < max; i++) { PropGet(); } ts = DateTime.Now - time; Console.Write("泛型委托取值方法:" + ts.TotalMilliseconds + "<br/>"); Console.Write("v:" + d.Name + "<br/>"); //表达式树赋值方法 d.Name = -1; LmdSet(typeof(EmitData), "Name"); time = DateTime.Now; for (int i = 0; i < max; i++) { _lmdSetProp(d, i); } ts = DateTime.Now - time; Console.Write("表达式树赋值方法:" + ts.TotalMilliseconds + "<br/>"); Console.Write("v:" + d.Name + "<br/>"); //表达式树取值方法 d.Name = -132; LmdGet(typeof(EmitData), "Name"); time = DateTime.Now; for (int i = 0; i < max; i++) { _lmdGetProp(d); } ts = DateTime.Now - time; Console.Write("表达式树取值方法:" + ts.TotalMilliseconds + "<br/>"); Console.Write("v:" + _lmdGetProp(d) + "<br/>"); //EMIT动态方法赋值 d.Name = -1; BuildEmitMethod(d.GetType(), "Name"); time = DateTime.Now; for (int i = 0; i < max; i++) { EmitSetValue(d, i); } ts = DateTime.Now - time; Console.Write("EMIT动态方法:" + ts.TotalMilliseconds + "<br/>"); Console.Write("v:" + d.Name + "<br/>"); }