C # syntax sugar: ReflectionSugar generic reflection class,

Source: Internet
Author: User

C # syntax sugar: ReflectionSugar generic reflection class,

Easy to use:

ReflectionSugar rs = new ReflectionSugar (100); // cache for 100 seconds. If this parameter is left blank, the cache is not cached by default.

Rs. Why?

 

Performance test:

Performance test source code:

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

Using SyntacticSugar; 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) {// performance test class PerformanceTest p = new PerformanceTest (); p. setCount (100000); // number of cycles (default: 1) p. setIs Multithread (false); // whether to enable multi-thread testing (default: false) /***************************** CreateInstance ******** * ********************** // cache p. execute (I =>{ CreateInstanceByCache (); // call function}, message =>{ Response. write (message) ;}); // total execution time: 0.09901 seconds // No cache p. execute (I =>{ CreateInstanceNoCache (); // call function}, message =>{ Response. write (message) ;}); // total execution time: 0.32002 seconds/******************************* Execu TeMethod ******************************** // cache p. execute (I =>{ ExecuteMethodByCache (); // call the function}, message =>{ Response. write (message) ;}); // total execution time: 0.36202 seconds // No cache p. execute (I =>{ ExecuteMethodNoCache (); // call the function}, message =>{ Response. write (message) ;}); // total execution time: 1.35508 seconds/****************************** ExecuteMethod ****** * ************************ // cache p. execute (I => {ExecuteMetho DByCache (); // call function}, message => {Response. write (message) ;}); // total execution time: 0.36202 seconds // No cache p. execute (I =>{ ExecuteMethodNoCache (); // call the function}, message =>{ Response. write (message) ;}); // total execution time: 1.35508 seconds/****************************** LoadFile ****** * ************************ // cache p. execute (I =>{ LoadFileByCache (); // call function}, message =>{ Response. write (message) ;}); // total execution time: 0.11801 // No cache p. Execute (I =>{ LoadFileNoCache (); // call function}, message =>{ Response. write (message) ;}); // total execution time: 4.89628 seconds // other methods will not be tested} // obtain the real-column private static void CreateInstanceByCache () {ReflectionSugar rs = new ReflectionSugar (100); // cache for 100 seconds var f = rs. createInstance <FileSugar> ("SyntacticSugar. fileSugar "," SyntacticSugar ");} // obtain the real-column private static void CreateInstanceNoCache () {string path =" SyntacticSugar. fi LeSugar, SyntacticSugar "; // namespace. type name, assembly Type o = Type. getType (path); // The loading type FileSugar obj = (FileSugar) Activator. createInstance (o, true); // create an instance based on the Type} // execute the private static void ExecuteMethodByCache () {ReflectionSugar rs = new ReflectionSugar (100 ); // cache for 100 seconds var path = rs. executeMethod ("SyntacticSugar", "FileSugar", "GetMapPath ","~ /");} // Execution function private static void ExecuteMethodNoCache () {ReflectionSugar rs = new ReflectionSugar (0); // cache 0 s var path = rs. executeMethod ("SyntacticSugar", "FileSugar", "GetMapPath ","~ /");} // Load Assembly private static void LoadFileByCache () {ReflectionSugar rs = new ReflectionSugar (100); // cache Assembly ams = rs for 100 seconds. loadFile (@ "D: \ \ SyntacticSugar \ bin \ Debug \ SyntacticSugar. dll ");} // load Assembly private static void LoadFileNoCache () {ReflectionSugar rs = new ReflectionSugar (0); // cache Assembly ams = rs for 100 seconds. loadFile (@ "D: \ \ SyntacticSugar \ bin \ Debug \ SyntacticSugar. dll ");}}}

  

 

Source code of the reflection class:

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> /// ** Description: Reflection generic class /// ** Creation Time: // ** modification time: -// ** modifier: sunkaixuan // * instructions for use: 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> // The cache time. If the value is 0, the cache is not cached. The default value is 0 seconds. Unit: seconds) /// </summary> public ReflectionSugar (int time = 0) {_ time = time ;} /// <summary> /// create an object instance /// </summary> /// <typeparam name = "T"> </typeparam> /// <param name = "fullName"> namespace. type name </param> /// <param name =" SemblyName "> assembly (dll name) </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; // namespace. type name, assembly Type o = Type. getType (path); // The loading type object obj = Activator. createInstance (o, true); // create an instance va Based on the Type R reval = (T) obj; if (_ isCache) Add <T> (key, reval, _ time); return reval; // type conversion and return} // <summary> // create an object instance // </summary> /// <typeparam name = "T"> Create an object </typeparam> // <param name = "assemblyName"> name of the Assembly where the type is located (dll name) </param> /// <param name = "nameSpace"> type nameSpace </param> /// <param name = "className"> type name </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; // namespace. type name // This is the first way to write object ect = Assembly. load (assemblyName ). createInstance (fullName); // load the Assembly and create the namespace in the Assembly. type name instance var reval = (T) ect; // type conversion and return if (_ isCache) Add <T> (key, reval, _ time); return Reval; // The second method: // string path = fullName + "," + assemblyName; // namespace. type name, assembly // Type o = Type. getType (path); // loading type // object obj = Activator. createInstance (o, true); // create an instance based on the Type // return (T) obj; // type conversion and return} catch {// exception, return type default value var reval = default (T); if (_ isCache) Add <T> (key, reval, _ time); return reval; // type conversion }}/// <summary> // load the Assembly /// </summary> /// <param name = "path"> </param>/ // <return S> </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> /// obtain the type according to the Assembly // </summary> /// <param name = "asm"> Assembly object </param> /// <returns> </returns> public Type GetTypeByAssembly (Ass Embly 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> // return the current System. all public attributes of 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> /// execution method based on characters /// </summary> /// <par Am name = "nameSpace"> nameSpace </param> /// <param name = "className"> class name </param> /// <param name = "MethodName"> method name </param> /// <param name = "parameters"> parameter </param> /// <returns> returns the object type </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 {// dynamically searches for the required class from the Assembly, creates an instance using the system activator, and obtains its Type type = Assembly. load (nameSpace ). createInstance (nameSpace + ". "+ className ). getType (); // defines the number, sequence, and Type of parameters. Type [] parametersLength; if (parameters! = Null) {// create a parameter bucket with parameters and set the Type parametersLength = new Type [parameters. length]; int I = 0; foreach (object obj in parameters) {parametersLength. setValue (obj. getType (), I); I ++ ;}} else {// if no parameter is specified, the parameter parametersLength = new Type [0];} // find the specified method methodinfo = type. getMethod (MethodName, parametersLength); if (_ isCache) Add <MethodInfo> (key, methodinfo, _ time );} // if it is a static method, execute (non-static I have not tried) if (methodinfo. isSt Atic) {// call the function return methodinfo. invoke (null, parameters);} return null;} # region helper private string GetKey (params string [] keyElementArray) {return string. join ("", keyElementArray );} /// <summary> /// insert cache /// </summary> /// <param name = "key"> key </param> /// <param name = "value"> value </param> // <param name = "cacheDurationInSeconds"> expiration time in seconds </param> private void Add <V> (string key, V value, Int cacheDurationInSeconds) {Add (key, value, cacheDurationInSeconds, CacheItemPriority. default);} // <summary> // insert cache. /// </summary> /// <param name = "key"> key </param> /// <param name = "value"> value </param>/ // <param name = "cacheDurationInSeconds"> expiration time, in seconds </param> // <param name = "priority"> cache item attribute </param> private void Add <v> (string key, V value, int cacheDurationInSeconds, CacheItemPriority prio Rity) {string keyString = key; HttpRuntime. cache. insert (keyString, value, null, DateTime. now. addSeconds (cacheDurationInSeconds), Cache. noSlidingExpiration, priority, null) ;}/// <summary> /// insert cache. /// </summary> /// <param name = "key"> key </param> /// <param name = "value"> value </param>/ // <param name = "cacheDurationInSeconds"> expiration time, in seconds </param> // <param name = "priority"> cache item attribute </param> private void Ad D <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> /// check whether the key exists /// </summary> /// <param name = "key"> key </param> /// <returns >/// <c> true </c> does not exist <c> f Alse </c>. // </returns> private bool ContainsKey (string key) {return HttpRuntime. Cache [key]! = Null;} // <summary> // obtain the Cache based on the key // </summary> private V Get <V> (string key) {return (V) httpRuntime. cache [key] ;}# endregion // PropertyInfo get set description // T. getProperty ("key "). getValue (obj, null); // read a key value // T. getProperty ("key "). setValue (obj, "", null); // write a value to key /// note that if it is a dictionary // T. getProperty ("Item "). getValue (obj, new [] {"id"}); // get the Item first and then use new [] {put the specified key here }}}

  

Summary:

As long as the external DLL File Cache is not reflected, the performance can be improved by three times. If the external DLL file is reflected, it can be improved by more than 40 times. This is only because the number of times of the test results is too large, and the performance gap is larger.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.