推荐一个快速反射调用的类

使用传统的.net反射机制,调用类的方法时,在调用频率大的情况下,会感觉速度很慢。最近浏览 卢彦 的博客时,找到一个他改进后的反射调用类。试用以后感觉效率明显提高,特推荐给大家。作者重新实现了,反射调用方法,但是调用接口和.net原有方法一致。而且调用时抛出的异常为所调用类的实际异常,不像传统方式返回为包装异常。
文章来源:
http://www.codeproject.com/csharp/FastMethodInvoker.asp

快速反射调用类
None.gif using  System;
None.gif
using  System.Collections.Generic;
None.gif
using  System.Text;
None.gif
using  System.Reflection;
None.gif
using  System.Reflection.Emit;
None.gif
None.gif
namespace  FastMethodInvoker
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif    
class FastInvoke
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
public delegate object FastInvokeHandler(object target, object[] paramters);
InBlock.gif
InBlock.gif        
static object InvokeMethod(FastInvokeHandler invoke, object target, params object[] paramters)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
return invoke(null, paramters);
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
public static FastInvokeHandler GetMethodInvoker(MethodInfo methodInfo)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif            DynamicMethod dynamicMethod 
= new DynamicMethod(string.Empty, typeof(object), new Type[] dot.giftypeof(object), typeof(object[]) }, methodInfo.DeclaringType.Module);
InBlock.gif            ILGenerator il 
= dynamicMethod.GetILGenerator();
InBlock.gif            ParameterInfo[] ps 
= methodInfo.GetParameters();
InBlock.gif            Type[] paramTypes 
= new Type[ps.Length];
InBlock.gif            
for (int i = 0; i < paramTypes.Length; i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
if (ps[i].ParameterType.IsByRef)
InBlock.gif                    paramTypes[i] 
= ps[i].ParameterType.GetElementType();
InBlock.gif                
else
InBlock.gif                    paramTypes[i] 
= ps[i].ParameterType;
ExpandedSubBlockEnd.gif            }

InBlock.gif            LocalBuilder[] locals 
= new LocalBuilder[paramTypes.Length];
InBlock.gif
InBlock.gif            
for (int i = 0; i < paramTypes.Length; i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                locals[i] 
= il.DeclareLocal(paramTypes[i], true);
ExpandedSubBlockEnd.gif            }

InBlock.gif            
for (int i = 0; i < paramTypes.Length; i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                il.Emit(OpCodes.Ldarg_1);
InBlock.gif                EmitFastInt(il, i);
InBlock.gif                il.Emit(OpCodes.Ldelem_Ref);
InBlock.gif                EmitCastToReference(il, paramTypes[i]);
InBlock.gif                il.Emit(OpCodes.Stloc, locals[i]);
ExpandedSubBlockEnd.gif            }

InBlock.gif            
if (!methodInfo.IsStatic)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                il.Emit(OpCodes.Ldarg_0);
ExpandedSubBlockEnd.gif            }

InBlock.gif            
for (int i = 0; i < paramTypes.Length; i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
if (ps[i].ParameterType.IsByRef)
InBlock.gif                    il.Emit(OpCodes.Ldloca_S, locals[i]);
InBlock.gif                
else
InBlock.gif                    il.Emit(OpCodes.Ldloc, locals[i]);
ExpandedSubBlockEnd.gif            }

InBlock.gif            
if (methodInfo.IsStatic)
InBlock.gif                il.EmitCall(OpCodes.Call, methodInfo, 
null);
InBlock.gif            
else
InBlock.gif                il.EmitCall(OpCodes.Callvirt, methodInfo, 
null);
InBlock.gif            
if (methodInfo.ReturnType == typeof(void))
InBlock.gif                il.Emit(OpCodes.Ldnull);
InBlock.gif            
else
InBlock.gif                EmitBoxIfNeeded(il, methodInfo.ReturnType);
InBlock.gif
InBlock.gif            
for (int i = 0; i < paramTypes.Length; i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
if (ps[i].ParameterType.IsByRef)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    il.Emit(OpCodes.Ldarg_1);
InBlock.gif                    EmitFastInt(il, i);
InBlock.gif                    il.Emit(OpCodes.Ldloc, locals[i]);
InBlock.gif                    
if (locals[i].LocalType.IsValueType)
InBlock.gif                        il.Emit(OpCodes.Box, locals[i].LocalType);
InBlock.gif                    il.Emit(OpCodes.Stelem_Ref);
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

InBlock.gif
InBlock.gif            il.Emit(OpCodes.Ret);
InBlock.gif            FastInvokeHandler invoder 
= (FastInvokeHandler)dynamicMethod.CreateDelegate(typeof(FastInvokeHandler));
InBlock.gif            
return invoder;
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
private static void EmitCastToReference(ILGenerator il, System.Type type)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
if (type.IsValueType)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                il.Emit(OpCodes.Unbox_Any, type);
ExpandedSubBlockEnd.gif            }

InBlock.gif            
else
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                il.Emit(OpCodes.Castclass, type);
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
private static void EmitBoxIfNeeded(ILGenerator il, System.Type type)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
if (type.IsValueType)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                il.Emit(OpCodes.Box, type);
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
private static void EmitFastInt(ILGenerator il, int value)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
switch (value)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
case -1:
InBlock.gif                    il.Emit(OpCodes.Ldc_I4_M1);
InBlock.gif                    
return;
InBlock.gif                
case 0:
InBlock.gif                    il.Emit(OpCodes.Ldc_I4_0);
InBlock.gif                    
return;
InBlock.gif                
case 1:
InBlock.gif                    il.Emit(OpCodes.Ldc_I4_1);
InBlock.gif                    
return;
InBlock.gif                
case 2:
InBlock.gif                    il.Emit(OpCodes.Ldc_I4_2);
InBlock.gif                    
return;
InBlock.gif                
case 3:
InBlock.gif                    il.Emit(OpCodes.Ldc_I4_3);
InBlock.gif                    
return;
InBlock.gif                
case 4:
InBlock.gif                    il.Emit(OpCodes.Ldc_I4_4);
InBlock.gif                    
return;
InBlock.gif                
case 5:
InBlock.gif                    il.Emit(OpCodes.Ldc_I4_5);
InBlock.gif                    
return;
InBlock.gif                
case 6:
InBlock.gif                    il.Emit(OpCodes.Ldc_I4_6);
InBlock.gif                    
return;
InBlock.gif                
case 7:
InBlock.gif                    il.Emit(OpCodes.Ldc_I4_7);
InBlock.gif                    
return;
InBlock.gif                
case 8:
InBlock.gif                    il.Emit(OpCodes.Ldc_I4_8);
InBlock.gif                    
return;
ExpandedSubBlockEnd.gif            }

InBlock.gif
InBlock.gif            
if (value > -129 && value < 128)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                il.Emit(OpCodes.Ldc_I4_S, (SByte)value);
ExpandedSubBlockEnd.gif            }

InBlock.gif            
else
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                il.Emit(OpCodes.Ldc_I4, value);
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif

效果测试程序
None.gif using  System;
None.gif
using  System.Reflection;
None.gif
using  System.Reflection.Emit;
None.gif
using  System.Collections.Generic;
None.gif
using  System.Text;
None.gif
using  System.Diagnostics;
None.gif
None.gif
namespace  FastMethodInvoker
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif    
class Program
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
static void Main(string[] args)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif
InBlock.gif            Type t 
= typeof(Person);
InBlock.gif            MethodInfo methodInfo 
= t.GetMethod("Say");
InBlock.gif            Person person 
= new Person();
InBlock.gif            
string word = "hello";
InBlock.gif            Person p 
= null;
ExpandedSubBlockStart.gifContractedSubBlock.gif            
object[] param = new object[] dot.gif{ word, p, 3 };
InBlock.gif            
int TestTimes = 100000//测试次数,可自行调节看效果
InBlock.gif

ContractedSubBlock.gifExpandedSubBlockStart.gif            
传统方式反射#region 传统方式反射
InBlock.gif            
try
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                Stopwatch watch 
= new Stopwatch();
InBlock.gif                watch.Start();
InBlock.gif                
for (int i = 0; i < TestTimes; i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    methodInfo.Invoke(person, param);
ExpandedSubBlockEnd.gif                }

InBlock.gif                watch.Stop();
InBlock.gif                Console.WriteLine(TestTimes.ToString() 
+ " times invoked by Reflection: " + watch.ElapsedMilliseconds + "ms");
ExpandedSubBlockEnd.gif            }

InBlock.gif            
catch (System.Exception ex)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                Console.WriteLine(
"传统方式反射 直接错误:" + ex.Message);
InBlock.gif                Console.WriteLine(
"传统方式反射 内部错误:" + ex.InnerException.Message);
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif            
#endregion

InBlock.gif
ContractedSubBlock.gifExpandedSubBlockStart.gif            
快速反射#region 快速反射
InBlock.gif            
try
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                Stopwatch watch1 
= new Stopwatch();
InBlock.gif                FastInvoke.FastInvokeHandler fastInvoker 
= FastInvoke.GetMethodInvoker(methodInfo);
InBlock.gif                watch1.Start();
InBlock.gif                
for (int i = 0; i < TestTimes; i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    fastInvoker(person, param);
ExpandedSubBlockEnd.gif                }

InBlock.gif                watch1.Stop();
InBlock.gif                Console.WriteLine(TestTimes.ToString() 
+ " times invoked by FastInvoke: " + watch1.ElapsedMilliseconds + "ms");
ExpandedSubBlockEnd.gif            }

InBlock.gif            
catch (System.Exception ex)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                Console.WriteLine(
"快速反射 错误:" + ex.Message);
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif            
#endregion

InBlock.gif
ContractedSubBlock.gifExpandedSubBlockStart.gif            
直接调用#region 直接调用
InBlock.gif            
try
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                Stopwatch watch2 
= new Stopwatch();
InBlock.gif                watch2.Start();
InBlock.gif                
for (int i = 0; i < TestTimes; i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    person.Say(
ref word, out p, 3);
ExpandedSubBlockEnd.gif                }

InBlock.gif                watch2.Stop();
InBlock.gif                Console.WriteLine(TestTimes.ToString() 
+ " times invoked by DirectCall: " + watch2.ElapsedMilliseconds + "ms");
ExpandedSubBlockEnd.gif            }

InBlock.gif            
catch (System.Exception ex)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                Console.WriteLine(
"直接调用 错误:" + ex.Message);
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif            
#endregion

InBlock.gif            
InBlock.gif            Console.ReadLine();
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    
public class Person
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
public void Say(ref string word, out Person p, int avi)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            word 
= "ttt" + avi.ToString();
InBlock.gif            p 
= new Person();
InBlock.gif
InBlock.gif            
//throw new System.Exception("出错了哦");
ExpandedSubBlockEnd.gif
        }

ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值