导航

字典缓存和泛型缓存

Posted on 2017-08-16 18:33  清浅ヾ  阅读(303)  评论(0编辑  收藏  举报
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace 缓存
 7 {
 8     class Program
 9     {
10         static void Main(string[] args)
11         {
12             //字典缓存
13             {
14                 for (int i = 0; i < 5; i++)
15                 {
16                     Console.WriteLine(DictionaryCache.GetCache<int>());
17                     Console.WriteLine(DictionaryCache.GetCache<string>());
18                     Console.WriteLine(DictionaryCache.GetCache<Peoele>());
19                     Console.WriteLine(DictionaryCache.GetCache<Student>());
20                     
21                 }
22             }
23             //泛型缓存
24             {
25                 for (int i = 0; i < 5; i++)
26                 {
27                     Console.WriteLine(GenericCache<int>.GetCache());
28                     Console.WriteLine(GenericCache<string>.GetCache());
29                     Console.WriteLine(GenericCache<Peoele>.GetCache());
30                     Console.WriteLine(GenericCache<Student>.GetCache());
31                 }
32             }
33            
34             Console.ReadLine();
35         }
36     }
37 
38     /// <summary>
39     /// 字典缓存,静态属性常驻内存
40     /// </summary>
41     public class DictionaryCache
42     {
43         private static Dictionary<string, object> _directory = null;
44         static DictionaryCache()
45         {
46             Console.WriteLine("这是一个静态构造函数");
47             _directory = new Dictionary<string, object>();
48         }
49         public static object GetCache<T>()
50         {
51             Type type = typeof(T);
52             //如果静态字典中不包含该类型时,即可加入
53             if (!_directory.ContainsKey(type.Name))
54             {
55                 _directory[type.Name] = string.Format("{0}_{1}",typeof(T).FullName,DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss"));
56             }
57             return _directory[type.Name]; 
58         }
59     }
60 
61 
62     /// <summary>
63     /// 泛型缓存
64     /// 每个不同的T类型,都会生成不同的一份副本
65     /// 适合不同的类型,需要缓存一份数据的场景,效率高
66     /// 缺点:不能清除缓存
67     /// </summary>
68     /// <typeparam name="T"></typeparam>
69     public class GenericCache<T>
70     {
71         private static string _Typetime ="";
72         static GenericCache()
73         {
74             Console.WriteLine("这是一个静态构造函数");
75             _Typetime = string.Format("{0}_{1}",typeof(T),DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss"));
76         }
77         public static string GetCache()
78         {
79             return _Typetime;
80         }
81     }
82 
83     public class Peoele
84     {
85         public int id { get; set; }
86         public string name { get; set; }
87     }
88     public class Student
89     {
90         public int id { get; set; }
91         public string name { get; set; }
92     }
93 }