Net Core教程

C#缓存类

本文主要是介绍C#缓存类,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
 1     public class CacheHelper
 2     {
 3         /// <summary>
 4         /// 创建缓存项的文件
 5         /// </summary>
 6         /// <param name="key">缓存Key</param>
 7         /// <param name="obj">object对象</param>
 8         public static void Insert(string key, object obj)
 9         {
10             //创建缓存
11             HttpContext.Current.Cache.Insert(key, obj);
12         }
13         /// <summary>
14         /// 移除缓存项的文件
15         /// </summary>
16         /// <param name="key">缓存Key</param>
17         public static void Remove(string key)
18         {
19             //创建缓存
20             HttpContext.Current.Cache.Remove(key);
21         }
22         /// <summary>
23         /// 创建缓存项的文件依赖
24         /// </summary>
25         /// <param name="key">缓存Key</param>
26         /// <param name="obj">object对象</param>
27         /// <param name="fileName">文件绝对路径</param>
28         public static void Insert(string key, object obj, string fileName)
29         {
30             //创建缓存依赖项
31             CacheDependency dep = new CacheDependency(fileName);
32             //创建缓存
33             HttpContext.Current.Cache.Insert(key, obj, dep);
34         }
35 
36         /// <summary>
37         /// 创建缓存项过期
38         /// </summary>
39         /// <param name="key">缓存Key</param>
40         /// <param name="obj">object对象</param>
41         /// <param name="expires">过期时间(分钟)</param>
42         public static void Insert(string key, object obj, int expires)
43         {
44             HttpContext.Current.Cache.Insert(key, obj, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, expires, 0));
45         }
46 
47         /// <summary>
48         /// 获取缓存对象
49         /// </summary>
50         /// <param name="key">缓存Key</param>
51         /// <returns>object对象</returns>
52         public static object Get(string key)
53         {
54             if (string.IsNullOrEmpty(key))
55             {
56                 return null;
57             }
58             return HttpContext.Current.Cache.Get(key);
59         }
60 
61         /// <summary>
62         /// 获取缓存对象
63         /// </summary>
64         /// <typeparam name="T">T对象</typeparam>
65         /// <param name="key">缓存Key</param>
66         /// <returns></returns>
67         public static T Get<T>(string key)
68         {
69             object obj = Get(key);
70             return obj == null ? default(T) : (T)obj;
71         }
72 
73     }

 

这篇关于C#缓存类的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!