泛型缓存

每个不同的T,都会生成一份不同的副本适合不同类型,需要缓存一份数据 的场景,效率高,

第一次进来都会读取构造函数中创建值,而第二次进来就不会传进入构造函数中创建值,,因为已经缓存好了数据

static void Main(string[] args)
        {
            PropertyStr<Student>.Get();
            PropertyStr<Student>.Get();
            PropertyStr<Person>.Get();
            PropertyStr<Person>.Get();
            Console.Read();
        }
public static class PropertyStr<T> where T:class
    {
        private static string t = null; //必须全都是静态的,构造函数里需要传出去的结果是什么类型的,这里就是什么类型的,比如Func<TIn,TOut>
        static PropertyStr()
        {
            t = string.Join(",", typeof(T).GetProperties().ToList());
            Console.WriteLine($"{typeof(T).Name}缓存好了");
        }
        public static void Get()
        {
            Console.WriteLine(t);
        }
    }
View Code

结果:

原文地址:https://www.cnblogs.com/jiangcm/p/11300483.html