1.泛型(Generic)

1、泛型緩存

泛型就是封裝,將重複的工做簡單化函數

1.泛型方法spa

public static void Show<T>(T tParameter)
{
  Console.WriteLine("This is {0}, parameter = {1}, type = {2}", typeof(CommonMethod).Name, tParameter.GetType(), tParameter);
}

2.泛型類code

public class GenericClass<T>{}

3.泛型接口orm

public interface GenericInterface<I>{}

4.泛型委託
blog

public delegate void Do<T>();

5.泛型約束接口

public static void Show<T>(T tParameter) where T : People//基類約束
                                       //where T : ISport//接口約束
{
  Console.WriteLine("This is {0}, parameter = {1}, type = {2}", typeof(CommonMethod).Name, tParameter.GetType(), tParameter);
  Console.WriteLine($"{tParameter.Id} {tParameter.Name}");
}
public T Get<T>(T t)
//where T : class//引用類型約束,才能夠返回null //where T: struct//值類型約束 where T: new()//無參構造函數約束 {   //return null;   //return default(T);//default是個關鍵字,會根據T的類型去獲取一個值   return new T();//只要有無參數構造函數,均可以傳進來   //throw new Exception(); }

6.泛型緩存string

    /// <summary>
    /// 每一個不一樣的T,都會生成一份不一樣的副本
    /// 適合不一樣類型,須要緩存一份數據的場景,效率高
    /// 侷限:只能爲某一類型緩存
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class GenericCache<T>
    {
        static GenericCache()
        {
            Console.WriteLine("This is GenericCache 靜態構造函數");
            _TypeTime = string.Format("{0}_{1}", typeof(T).FullName, DateTime.Now.ToString("yyyyMMddHHmmss.fff"));
        }

        private static string _TypeTime = "";

        public static string GetCache()
        {
            return _TypeTime;
        }
    }7.泛型協變(out-返回值)、逆變(in-參數)
相關文章
相關標籤/搜索