C#语法糖之 ReflectionSugar 通用反射类

用法很简单:

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

 rs.有嘛点嘛

 

性能测试:

性能测试类源码:

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
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");
        }
    }
}

  

 

反射类源码: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
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倍以上,这只是我的测试结果 循环次数超多性能差距越大

posted @   阿妮亚  阅读(1748)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示