一个高效反射类

1.项目中有需要用到反射的地方,仔细研究了下反射,其效率并不高

还好微软提供了IL的编程方法,自己实现了一个高效反射类

 

下面举些常用例子:

我们反射出.NETFramework中的一个未公开的类 SessionStateUtility 并调用其私有方法 Deserialize

1 public static SessionStateStoreData Deserialize(HttpContext context, Stream stream)

2         {

3            DynamicMethodPrivoder _sessionStateUtility=new DynamicMethodPrivoder(typeof(SessionStateUtility), null);

5             return _sessionStateUtility.MethodInvoke("Deserialize", context, stream) as SessionStateStoreData;

6         }

注意:由于DynamicMethodPrivoder.Deserialize 是静态方法  所以DynamicMethodPrivoder构造的第二个参数为null

 

我们反射出 HttpContext下的一个 HttpSessionStateContainer 对象中 的私有字段 _sessionItems并获取它的值

1 public static SessionStateStoreData GetSessionStoreDate(HttpContext context)

2         {

3             IHttpSessionState container = SessionStateUtility.GetHttpSessionStateFromContext(context);

4             Type _containerType = typeof(HttpSessionStateContainer);

5             DynamicMethodPrivoder _containerPrivoder = new DynamicMethodPrivoder(_containerType, container);

6             ISessionStateItemCollection sessionItems = _containerPrivoder.Field("_sessionItems") as ISessionStateItemCollection;

7             HttpStaticObjectsCollection staticObjects = container.StaticObjects;

8             return new SessionStateStoreData(sessionItems, staticObjects, container.Timeout);

9         }


废话不多说了  直接上源码:http://files.cnblogs.com/dint/DynamicMethodPrivoder.rar

 

你可能感兴趣的:(反射)