using System.Collections.Generic;

1.泛型引入

      泛型方法:

 1 /// <summary>
 2     /// When You meet some the same things, especially on methods, you could use the generic.
 3     /// </summary>
 4     class TestGeneric
 5     {
 6         /// <summary>
 7         /// obj method
 8         /// </summary>
 9         /// <param name="obj"></param>
10         public static void ShowObject(object obj)
11         {
12             Console.WriteLine("class is {0} , parameter = {1} , value = {2}",
13                 typeof(TestGeneric).Name, obj.GetType().Name, obj);
14         }
15         /// <summary>
16         /// generic Method
17         /// from .net framework 2.0, updated CLR
18         /// delay for statement
19         /// </summary>
20         /// <typeparam name="T"></typeparam>
21         /// <param name="t"></param>
22         public static void ShowObject<T>(T t)
23         {
24             Console.WriteLine("class is {0} , parameter = {1} , value = {2}",
25                 typeof(TestGeneric).Name, t.GetType().Name, t);
26         }
27     }
泛型方法

  测试代码:

1                 //int i = 5;
2                 //float j = 2.0f;
3                 //TestGeneric.ShowObject(i);
4                 //TestGeneric.ShowObject<float>(j);
5                 //TestGeneric.ShowObject(j);//Do not define the type, but it will auto-acculate the type from the parameter.              
6                 //Console.WriteLine(typeof(List<>));
7                 //Console.WriteLine(typeof(Dictionary<,>));                
测试代码

2.泛型类

 1  /// <summary>
 2     /// generic Class
 3     /// </summary>
 4     /// <typeparam name="T"></typeparam>
 5     /// <typeparam name="Jungle"></typeparam>
 6     public class GenericClass<T, Jungle>
 7     {
 8         public void Show(T t)
 9         {
10 
11         }
12 
13         public Jungle Get()
14         {
15             return default(Jungle);
16         }
17     }
View Code

3.泛型接口

1 /// <summary>
2     /// generic Interface
3     /// </summary>
4     /// <typeparam name="T"></typeparam>
5     public interface IStudy<T>
6     {
7         void Study();
8         T Study(T t);
9     }
View Code

4.泛型委托

1 /// <summary>
2     /// generic Delegate
3     /// </summary>
4     /// <typeparam name="EveryThing"></typeparam>
5     /// <returns></returns>
6     public delegate EveryThing GetHandler<EveryThing>();
View Code

5.泛型的继承

 1 /// <summary>
 2     /// Common Class
 3     /// </summary>
 4     public class Child
 5         //: GenericClass<T, Jungle> //Common class cannot directly inherit the Generic Class
 6         : GenericClass<int, string>, IStudy<string> // must be defined the type of inner, the same as the interface
 7     {
 8         public void Study()
 9         {
10             throw new NotImplementedException();
11         }
12 
13         public string Study(string t)
14         {
15             throw new NotImplementedException();
16         }
17     }
18 
19     /// <summary>
20     /// GenericClass
21     /// </summary>
22     /// <typeparam name="T"></typeparam>
23     /// <typeparam name="Jungle"></typeparam>
24     public class GenericChild<T, Jungle>
25         : GenericClass<T, String>, IStudy<string> // But GenericClass can directly inherit the Generic Class, so the same as interface
26     {
27         public void Study()
28         {
29             throw new NotImplementedException();
30         }
31 
32         public string Study(string t)
33         {
34             throw new NotImplementedException();
35         }
36     }
View Code

 6.out and In

 1 /// <summary>
 2     /// 只能放在接口或者委托的泛型参数前面
 3     /// out 协变covariant    修饰返回值 
 4     /// in  逆变contravariant  修饰传入参数
 5     /// From C#-4.0
 6     /// </summary>
 7     public class InAndOut
 8     {
 9         #region Bird,Sparrow
10         public class Bird
11         {
12             public int Id { get; set; }
13         }
14 
15         public class Sparrow : Bird
16         {
17             public string Name { get; set; }
18         }
19         #endregion
20 
21         
22         List<Bird> BirdList = new List<Bird>();
23         //List<Bird> BirdList1 = new List<Sparrow>();   //Error CS0029  Cannot implicitly convert type List<Bird> to List<Sparrow>, because of non-inheritance, evev though the Sparrow is inherited from the Bird.
24         List<Bird> birdList2 = new List<Sparrow>().Select(c => (Bird)c).ToList();//You can try this method.
25         IEnumerable<Bird> BirdListOut = new List<Sparrow>();//the convert automatically by Compiler.
26 
27         //out 协变covariant    修饰返回值
28         public interface ICustomerListOut<out T>
29         {
30             T Get();//只能作为返回值
31         }
32         public class CustomerListOut<T> : ICustomerListOut<T>
33         {
34             public T Get()
35             {
36                 return default(T);
37             }
38         }
39         ICustomerListOut<Bird> customerListout1 = new CustomerListOut<Bird>();
40         ICustomerListOut<Bird> customerListout2 = new CustomerListOut<Sparrow>();//Sparrow --> Bird
41 
42         //in  逆变contravariant  修饰传入参数
43         public interface ICustomerListIn<in T>//只能放在接口或者委托的泛型参数前面
44         {
45             void Show(T t);//只能作为传入参数
46         }
47         public class CustomerListIn<T> : ICustomerListIn<T>
48         {
49             public void Show(T t) { Console.WriteLine("customized contravariant"); }
50         }
51         ICustomerListIn<Sparrow> customerListIn1 = new CustomerListIn<Sparrow>();
52         ICustomerListIn<Sparrow> customerListIn2 = new CustomerListIn<Bird>();//Bird --> Sparrow
53 
54         //in + out
55         public interface IMyList<in inT, out outT>
56         {
57             //out只能是返回值, in只能是参数.
58             void Show(inT t);
59             outT Get();
60             outT Do(inT t);
61         }
62         public class MyList<T1, T2> : IMyList<T1, T2>
63         {
64             public void Show(T1 t) { Console.WriteLine(t.GetType().Name); }
65             public T2 Get() {
66                 Console.WriteLine(typeof(T2).Name);
67                 return default(T2);
68             }
69             public T2 Do(T1 t)
70             {
71                 Console.WriteLine(t.GetType().Name);
72                 return default(T2);
73             }
74         }
75         IMyList<Sparrow, Bird> myList1 = new MyList<Sparrow, Bird>();//正常情况
76         IMyList<Sparrow, Bird> myList2 = new MyList<Sparrow, Sparrow>();//协变-out
77         IMyList<Sparrow, Bird> myList3 = new MyList<Bird, Bird>();//逆变-in
78         IMyList<Sparrow, Bird> myList4 = new MyList<Bird, Sparrow>();//out+in
79 
80 
81     }
协变与逆变

 7. 泛型用于缓存

public class GenericCache
    {
        public static void Show()
        {
            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine(DictionaryCache.GetCache<int>());
                Thread.Sleep(10);
                Console.WriteLine(DictionaryCache.GetCache<long>());
                Thread.Sleep(10);
                Console.WriteLine(DictionaryCache.GetCache<DateTime>());
                Thread.Sleep(10);
                Console.WriteLine(DictionaryCache.GetCache<string>());
                Thread.Sleep(10);
                Console.WriteLine(DictionaryCache.GetCache<GenericCache>());
                Thread.Sleep(10);
            }

            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine(GenericCache<int>.GetCache());
                Thread.Sleep(10);
                Console.WriteLine(GenericCache<long>.GetCache());
                Thread.Sleep(10);
                Console.WriteLine(GenericCache<DateTime>.GetCache());
                Thread.Sleep(10);
                Console.WriteLine(GenericCache<string>.GetCache());
                Thread.Sleep(10);
                Console.WriteLine(GenericCache<GenericCache>.GetCache());
                Thread.Sleep(10);
            }
        }
    }

    /// <summary>
    /// 字典缓存:静态属性常驻内存
    /// 若执行5次,则是一个类-Dictionary,5个值放入字典。
    /// </summary>
    public class DictionaryCache
    {
        private static Dictionary<string, string> _TypeTimeDictionary = null;
        static DictionaryCache()
        {
            Console.WriteLine("DictionaryCache---静态构造函数!");
            _TypeTimeDictionary = new Dictionary<string, string>();
        }
        public static string GetCache<T>()
        {
            Type type = typeof(T);
            if (!_TypeTimeDictionary.ContainsKey(type.Name))
            {
                _TypeTimeDictionary[type.Name] = string.Format("{0}_{1}", typeof(T).FullName, DateTime.Now.ToString());
            }
            return _TypeTimeDictionary[type.Name];
        }
    }

    /// <summary>
    /// 每个不同的T,都会生成一份不同的副本
    /// 适合不同类型,需要缓存一份数据的场景,效率高
    /// 若执行5次,则是5个类,5个值_TypeTime。
    /// 缺陷:无法清除缓存
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class GenericCache<T>
    {
        static GenericCache()
        {
            Console.WriteLine("DictionaryCache---静态构造函数!");
            _TypeTime = string.Format("{0}_{1}", typeof(T).FullName, DateTime.Now.ToString("yyyyMMddHHmmss.fff"));
        }

        private static string _TypeTime = "";

        public static string GetCache()
        {
            return _TypeTime;
        }
    }
View Code

 

posted @ 2018-01-09 13:46  ~Jungle  Views(1523)  Comments(0Edit  收藏  举报