用法很简单:

ReflectionSugar rs = new ReflectionSugar(100);//缓存100秒 ,可以不填默认不缓存

rs.有嘛点嘛

 

性能测试:

性能测试类源码:

http://www.cnblogs.com/sunkaixuan/p/4540840.html

using SyntacticSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls; namespace Test.IO
{
public partial class ReflectionTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//性能测试类
PerformanceTest p = new PerformanceTest();
p.SetCount(100000);//循环次数(默认:1)
p.SetIsMultithread(false);//是否启动多线程测试 (默认:false) /******************************CreateInstance********************************/
//带cache
p.Execute(
i =>
{
CreateInstanceByCache();//调用函数
},
message => { Response.Write(message); }); //总共执行时间:0.09901秒 //不带cache
p.Execute(
i =>
{
CreateInstanceNoCache();//调用函数
},
message => { Response.Write(message); }); //总共执行时间:0.32002秒 /******************************ExecuteMethod********************************/
//带cache
p.Execute(
i =>
{
ExecuteMethodByCache();//调用函数
},
message => { Response.Write(message); }); //总共执行时间:0.36202秒 //不带cache
p.Execute(
i =>
{
ExecuteMethodNoCache();//调用函数
},
message => { Response.Write(message); }); //总共执行时间:1.35508秒 /******************************ExecuteMethod********************************/
//带cache
p.Execute(
i =>
{
ExecuteMethodByCache();//调用函数
},
message => { Response.Write(message); }); //总共执行时间:0.36202秒 //不带cache
p.Execute(
i =>
{
ExecuteMethodNoCache();//调用函数
},
message => { Response.Write(message); }); //总共执行时间:1.35508秒 /******************************LoadFile********************************/
//带cache
p.Execute(
i =>
{
LoadFileByCache();//调用函数
},
message => { Response.Write(message); }); //总共执行时间:0.11801 //不带cache
p.Execute(
i =>
{
LoadFileNoCache();//调用函数
},
message => { Response.Write(message); }); //总共执行时间:4.89628秒 //还有其它方法就不测试了
} //获取实列
private static void CreateInstanceByCache()
{
ReflectionSugar rs = new ReflectionSugar(100);//缓存100秒
var f = rs.CreateInstance<FileSugar>("SyntacticSugar.FileSugar", "SyntacticSugar");
}
//获取实列
private static void CreateInstanceNoCache()
{
string path = "SyntacticSugar.FileSugar,SyntacticSugar";//命名空间.类型名,程序集
Type o = Type.GetType(path);//加载类型
FileSugar obj = (FileSugar)Activator.CreateInstance(o, true);//根据类型创建实例
}
//执行函数
private static void ExecuteMethodByCache()
{
ReflectionSugar rs = new ReflectionSugar(100);//缓存100秒
var path = rs.ExecuteMethod("SyntacticSugar", "FileSugar", "GetMapPath", "~/");
}
//执行函数
private static void ExecuteMethodNoCache()
{
ReflectionSugar rs = new ReflectionSugar(0);//缓存0秒
var path = rs.ExecuteMethod("SyntacticSugar", "FileSugar", "GetMapPath", "~/");
}
//加载程序集
private static void LoadFileByCache()
{
ReflectionSugar rs = new ReflectionSugar(100);//缓存100秒
Assembly ams = rs.LoadFile(@"D:\学习\SyntacticSugar\SyntacticSugar\bin\Debug\SyntacticSugar.dll");
}
//加载程序集
private static void LoadFileNoCache()
{
ReflectionSugar rs = new ReflectionSugar(0);//缓存100秒
Assembly ams = rs.LoadFile(@"D:\学习\SyntacticSugar\SyntacticSugar\bin\Debug\SyntacticSugar.dll");
}
}
}

  

反射类源码: 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web;
using System.Web.Caching; namespace SyntacticSugar
{ /// <summary>
/// ** 描述:反射通用类
/// ** 创始时间:2010-2-28
/// ** 修改时间:-
/// ** 修改人:sunkaixuan
/// ** 使用说明: http://www.cnblogs.com/sunkaixuan/p/4635710.html
/// </summary>
public class ReflectionSugar
{
public static int Minutes = 60;
public static int Hour = 60 * 60;
public static int Day = 60 * 60 * 24;
private int _time = 0;
private bool _isCache { get { return _time > 0; } }
/// <summary>
/// 缓存时间,0为不缓存(默认值:0秒,单位:秒)
/// </summary>
public ReflectionSugar(int time = 0)
{
_time = time;
} /// <summary>
/// 创建对象实例
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="fullName">命名空间.类型名</param>
/// <param name="assemblyName">程序集(dll名称)</param>
/// <returns></returns>
public T CreateInstance<T>(string fullName, string assemblyName)
{
string key = GetKey("CreateInstance1", fullName, assemblyName);
if (_isCache)
if (ContainsKey(key))
{
return Get<T>(key);
}
string path = fullName + "," + assemblyName;//命名空间.类型名,程序集
Type o = Type.GetType(path);//加载类型
object obj = Activator.CreateInstance(o, true);//根据类型创建实例
var reval = (T)obj;
if (_isCache)
Add<T>(key, reval, _time);
return reval;//类型转换并返回
} /// <summary>
/// 创建对象实例
/// </summary>
/// <typeparam name="T">要创建对象的类型</typeparam>
/// <param name="assemblyName">类型所在程序集名称(dll名称)</param>
/// <param name="nameSpace">类型所在命名空间</param>
/// <param name="className">类型名</param>
/// <returns></returns>
public T CreateInstance<T>(string assemblyName, string nameSpace, string className)
{
string key = GetKey("CreateInstance2", assemblyName, nameSpace, className);
if (_isCache)
if (ContainsKey(key))
{
return Get<T>(key);
}
try
{
string fullName = nameSpace + "." + className;//命名空间.类型名
//此为第一种写法
object ect = Assembly.Load(assemblyName).CreateInstance(fullName);//加载程序集,创建程序集里面的 命名空间.类型名 实例
var reval = (T)ect;//类型转换并返回
if (_isCache)
Add<T>(key, reval, _time);
return reval;
//下面是第二种写法
//string path = fullName + "," + assemblyName;//命名空间.类型名,程序集
//Type o = Type.GetType(path);//加载类型
//object obj = Activator.CreateInstance(o, true);//根据类型创建实例
//return (T)obj;//类型转换并返回
}
catch
{
//发生异常,返回类型的默认值
var reval = default(T);
if (_isCache)
Add<T>(key, reval, _time);
return reval;//类型转换
}
}
/// <summary>
/// 加载程序集
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public Assembly LoadFile(string path)
{
string key = GetKey("LoadFile", path);
if (_isCache)
if (ContainsKey(key))
{
return Get<Assembly>(key);
}
Assembly asm = Assembly.LoadFile(path);
if (_isCache)
Add<Assembly>(key, asm, _time);
return asm;
} /// <summary>
/// 获取类型根据程序集
/// </summary>
/// <param name="asm">Assembly对象</param>
/// <returns></returns>
public Type GetTypeByAssembly(Assembly asm, string nameSpace, string className)
{
string key = GetKey("GetTypeByAssembly", nameSpace, className);
if (_isCache)
if (ContainsKey(key))
{
return Get<Type>(key);
}
Type type = asm.GetType(nameSpace + "." + className);
if (_isCache)
Add<Type>(key, type, _time);
return type;
} /// <summary>
/// 返回当前 System.Type 的所有公共属性。
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public PropertyInfo[] GetProperties(Type type)
{
string key = GetKey("GetProperties", type.FullName);
if (_isCache)
if (ContainsKey(key))
{
return Get<PropertyInfo[]>(key);
}
var reval = type.GetProperties();
if (_isCache)
Add<PropertyInfo[]>(key, reval, _time);
return reval;
} /// <summary>
/// 根据字符执行方法
/// </summary>
/// <param name="nameSpace">命名空间</param>
/// <param name="className">类名</param>
/// <param name="MethodName">方法名</param>
/// <param name="parameters">参数</param>
/// <returns>返回object类型</returns>
public object ExecuteMethod(string nameSpace, string className, string MethodName, params object[] parameters)
{
string key = GetKey("ExecuteMethod", nameSpace, className, MethodName, parameters.Length.ToString());
MethodInfo methodinfo = null;
if (_isCache&&ContainsKey(key))
{
methodinfo = Get<MethodInfo>(key);
}
else
{
//动态从程序集中查找所需要的类并使用系统激活器创建实例最后获取它的Type
Type type = Assembly.Load(nameSpace).CreateInstance(nameSpace + "." + className).GetType();
//定义参数的个数,顺序以及类型的存储空间;
Type[] parametersLength;
if (parameters != null)
{ //如果有参数创建参数存储空间并依次设置类型
parametersLength = new Type[parameters.Length];
int i = 0;
foreach (object obj in parameters)
{ parametersLength.SetValue(obj.GetType(), i);
i++; } }
else
{ //没有参数就为空
parametersLength = new Type[0]; } //查找指定的方法
methodinfo = type.GetMethod(MethodName, parametersLength);
if (_isCache)
Add<MethodInfo>(key, methodinfo, _time);
}
//如果是静态方法就执行(非静态我没试过)
if (methodinfo.IsStatic)
{ //调用函数
return methodinfo.Invoke(null, parameters); } return null; } #region helper
private string GetKey(params string[] keyElementArray)
{
return string.Join("", keyElementArray);
} /// <summary>
/// 插入缓存
/// </summary>
/// <param name="key"> key</param>
/// <param name="value">value</param>
/// <param name="cacheDurationInSeconds">过期时间单位秒</param>
private void Add<V>(string key, V value, int cacheDurationInSeconds)
{
Add(key, value, cacheDurationInSeconds, CacheItemPriority.Default);
} /// <summary>
/// 插入缓存.
/// </summary>
/// <param name="key">key</param>
/// <param name="value">value</param>
/// <param name="cacheDurationInSeconds">过期时间单位秒</param>
/// <param name="priority">缓存项属性</param>
private void Add<V>(string key, V value, int cacheDurationInSeconds, CacheItemPriority priority)
{
string keyString = key;
HttpRuntime.Cache.Insert(keyString, value, null, DateTime.Now.AddSeconds(cacheDurationInSeconds), Cache.NoSlidingExpiration, priority, null);
} /// <summary>
/// 插入缓存.
/// </summary>
/// <param name="key">key</param>
/// <param name="value">value</param>
/// <param name="cacheDurationInSeconds">过期时间单位秒</param>
/// <param name="priority">缓存项属性</param>
private void Add<V>(string key, V value, int cacheDurationInSeconds, CacheDependency dependency, CacheItemPriority priority)
{
string keyString = key;
HttpRuntime.Cache.Insert(keyString, value, dependency, DateTime.Now.AddSeconds(cacheDurationInSeconds), Cache.NoSlidingExpiration, priority, null);
} /// <summary>
/// key是否存在
/// </summary>
/// <param name="key">key</param>
/// <returns> /// 存在<c>true</c> 不存在<c>false</c>. /// /// </returns>
private bool ContainsKey(string key)
{
return HttpRuntime.Cache[key] != null;
} /// <summary>
///获取Cache根据key
/// </summary>
private V Get<V>(string key)
{
return (V)HttpRuntime.Cache[key];
}
#endregion //PropertyInfo GET SET说明
//T.GetProperty("key").GetValue(obj, null); //read a key value
//T.GetProperty("key").SetValue(obj, "", null); //write a value to key
////注意如果是字典
//T.GetProperty("Item").GetValue(obj, new [] {"id"}); //先拿Item 然后才通过 new[] {这里放指定的key}
}
}

  

总结:

只要不反射外部DLL文件缓存可以提高3倍性能,如果是反射外部DLL文件可以提高40倍以上,这只是我的测试结果 循环次数超多性能差距越大

C#语法糖之 ReflectionSugar 通用反射类的更多相关文章

  1. ReflectionSugar 通用反射类

    http://www.cnblogs.com/sunkaixuan/p/4635710.html

  2. Scala的apply unapply unapplySeq 语法糖

    apply 可以理解为注入 unapply unapplySeq 可以理解为提取 apply 与 unapply 虽然名字相近,但是使用起来区别挺大.apply有点像构造函数unapply主要是结合模 ...

  3. Python进阶-XVIII 封装、(属性、静态方法、类方法)语法糖、反射

    1.封装 类中的私有化:属性的私有化和方法的私有化 会用到私有的这个概念de场景 1.隐藏起一个属性 不想让类的外部调用 2.我想保护这个属性,不想让属性随意被改变 3.我想保护这个属性,不被子类继承 ...

  4. Java语法糖设计

    语法糖 Java语法糖系列,所以首先讲讲什么是语法糖.语法糖是一种几乎每种语言或多或少都提供过的一些方便程序员开发代码的语法,它只是编译器实现的一些小把戏罢了,编译期间以特定的字节码或者特定的方式对这 ...

  5. 看看C# 6.0中那些语法糖都干了些什么(中篇)

    接着上篇继续扯,其实语法糖也不是什么坏事,第一个就是吃不吃随你,第二个就是最好要知道这些糖在底层都做了些什么,不过有一点 叫眼见为实,这样才能安心的使用,一口气上五楼,不费劲. 一:字符串嵌入值 我想 ...

  6. C# 6.0新特性---语法糖

    转载:http://www.cnblogs.com/TianFang/p/3928172.html 所谓语法糖就是在编译器里写做文章,达到简化代码书写的目的,要慎重使用,省略过多不易理解. NULL检 ...

  7. 语法糖----JAVA

    语法糖 语法糖(Syntactic Sugar),也叫糖衣语法,是英国计算机科学家彼得·约翰·兰达(Peter J. Landin)发明的一个术语.指的是,在计算机语言中添加某种语法,这种语法能使程序 ...

  8. 语法糖(Syntactic sugar)

    语法糖(Syntactic sugar),是由Peter J. Landin(和图灵一样的天才人物,是他最先发现了Lambda演算,由此而创立了函数式编程)创造的一个词语,它意指那些没有给计算机语言添 ...

  9. 早期(编译器)优化--Java语法糖的味道

    1.泛型与类型擦除 泛型的本质是参数化类型的应用,也就是说所操作的数据类型被指定为一个参数.这种参数类型可以用在类.接口和方法的创建中,分别称为泛型类.泛型接口和泛型方法.在泛型没有出现之前,只能通过 ...

随机推荐

  1. iOS相册、相机、通讯录权限获取

    iOS相册.相机.通讯录权限获取 说明 这是本人写的一个工具,用以便利的处理各种权限获取的操作,目前提供相册.照相机.通讯录的权限获取操作,参考了 http://www.jianshu.com/p/a ...

  2. EWM ODO清理功能

    ERP OBD下传到EWM会自动产生拣货任务(通常做法),但如果EWM因库存不足或其它原因无法拣货时一般要差异确认,对ODO行项目进行0确认.但问题是零确认后EWM标准流程是无法回传ERP的. ERP ...

  3. 实施vertex compression所遇到的各种问题和解决办法

    关于顶点压缩,好处是可以减少带宽,一定程度提高加载速度,可以提高约5-10%的fps,特别是mobile上,简单描述就是: 压缩之前(32字节) position float3 12normal fl ...

  4. Android 代码混淆、第三方平台加固加密、渠道分发 完整教程(图文)

    第一步:代码混淆(注意引入的第三方jar) 在新版本的ADT创建项目时,混码的文件不再是proguard.cfg,而是project.properties和proguard-project.txt. ...

  5. Android 中的AIDL,Parcelable和远程服务

    Android 中的AIDL,Parcelable和远程服务      早期在学习期间便接触到AIDL,当时对此的运用也是一撇而过.只到近日在项目中接触到AIDL,才开始仔细深入.AIDL的作用    ...

  6. 旧手机作为USB无线网卡使用(分享WIFI、蓝牙连接)

    首先开启手机的WIFI或者蓝牙功能,建立访问互联网的连接,然后设置-更多-网络共享与便携热点,打开安卓手机USB网络共享功能,即可在计算机上通过手机(无电话卡.数据卡)访问互联网.而且此时手机一直在充 ...

  7. Expender Header 与 Content互斥展示

    Expender 在展开时,Header 不展示:不展开时,展示 Header <Expander dxlc:DockLayoutControl.Dock="Top" IsE ...

  8. [转]mongodb与mysql相比的优缺点

    原文地址:http://blog.sina.com.cn/s/blog_966e430001019s8v.html 与关系型数据库相比,MongoDB的优点:①弱一致性(最终一致),更能保证用户的访问 ...

  9. android之AlertDialog 点击其它区域自己主动消失

    遇到一个问题记录下来,在开发中使用了AlertDialog,想点击屏幕其它区域的时候让这个dialog消失,一開始不做不论什么设置,在小米手机能够正常显示,可是在三星中却有问题.后来发现少了一个属性: ...

  10. tomcat java.net.BindException: Cannot assign requested address 解决方法

    今天线上TOMCAT启动时遇到了下比较麻烦的问题,错误如下: 21-Apr-2016 15:14:19.077 SEVERE [main] org.apache.catalina.core.Stand ...