1语法基础_泛型


 泛型的个人见解:让类或者方法,从复制粘贴  变成单个的通用访问

1、泛型类、泛型方法、泛型接口、泛型委托

  /// 
    /// 泛型方法
    /// 
    public class GenericTest
    {
        public static void Show(T tParameter)
        {
            Console.WriteLine("This is {0},parameter={1},type={2}",
                typeof(CommonMethod), tParameter.GetType().Name, tParameter);
        }
    }

    /// 
    /// 泛型类型  就是一个类型 满足多个类型的需求
    /// 
    /// 
    public class GenericClass
    { 
    public T name{get;set;} }
public class ChildClass : GenericClass, GenericInterface { } public class ChildClass1 : GenericInterface<int> { } /// /// 泛型接口 就是一个接口 满足多个多个类型的需求 /// /// public interface GenericInterface { } /// /// 泛型委托 就是一个委托 满足多个多个类型的需求 /// /// public delegate void Do();

2、定义泛型缓存,用于性能优化,存的是hash 如果数据多了也会有性能问题

  ///  
    /// 1字典缓存:静态属性常驻内存  2根据不同类型会生成不同的副本 3泛型缓存本质上是一个泛型类
    /// 
    public class DictionaryCache
    {
        private static Dictionarystring> _TypeTimeDictionary = null;
        static DictionaryCache()
        {
            Console.WriteLine("This is DictionaryCache 静态构造函数");
            _TypeTimeDictionary = new Dictionarystring>();
        }
        public static string GetCache()
        {
            Type type = typeof(T);
            if (!_TypeTimeDictionary.ContainsKey(type))
            {
                _TypeTimeDictionary[type] = string.Format("{0}_{1}", typeof(T).FullName, DateTime.Now.ToString("yyyyMMddHHmmss.fff"));
            }
            return _TypeTimeDictionary[type];
        }
    }

 3.泛型 约束

    public static void Show(T tParameter)
           where T : People //基类约束,你只能是一个People ,所以这里参数只能传入People或者People子类
        //where T : ISports // 接口约束
        //where T : class // 引用类型约束  就只能传入引用类型的参数
        //where T : struct // 值类型约束   
        //where T : new()// 无参数构造偶函数约束
        //where T : class, new() // 泛型约束可以结合使用 ,用逗号分隔就OK
        {
           
        }

相关