泛型1

1. 延迟声明:把参数类型的声明,延迟到调用的时候推迟一切可以推迟的东西

2. 泛型不是语法糖,语法糖是编译器提供的功能;但是泛型是整个.net框架、CLR升级后增加的功能。

3. 普通方法在声明的时候知道参数类型;泛型方法在申明的时候不知道参数类型,用占位符的形式代替泛型方法;在编译后因为调用方指定了泛型类型,这时指定的类型替换了占位符;所以说编译后的泛型方法和普通方法是一样的,所以不会影响后面的性能运行。

4. 一个方法支持多种参数类型,性能无损耗。

5. 性能测试结果: 普通方法和泛型方法性能差不多,object方法因为要装箱拆箱,所以性能更差些。

 

普通方法:

        /// <summary>
        /// 接受int类型参数
        /// </summary>
        /// <param name="iParameter"></param>
        public static void ShowInt(int iParameter)
        {
            Console.WriteLine("This is {0}'s ShowInt,parameter={1},value={2}",
                typeof(CommonClass), iParameter.GetType(), iParameter);
        }

        /// <summary>
        /// 接受long类型参数
        /// </summary>
        /// <param name="lParameter"></param>
        public static void ShowLong(long  lParameter)
        {
            Console.WriteLine("This is {0}'s ShowLong,parameter={1},value={2}",
                typeof(CommonClass), lParameter.GetType(), lParameter);
        }

        /// <summary>
        /// 接受string类型参数
        /// </summary>
        /// <param name="sParameter"></param>
        public static void ShowString(string sParameter)
        {
            Console.WriteLine("This is {0}'s ShowString,parameter={1},value={2}",
                typeof(CommonClass), sParameter.GetType(), sParameter);
        }

 

object方法

        /// <summary>
        /// 1. object类型是一切类型的父类
        /// 2. 任何父类出现的地方,都可以用子类来代替
        /// </summary>
        /// <param name="oParameter"></param>
        public static void ShowObject(object oParameter)
        {
            Console.WriteLine("This is {0}'s ShowObject,parameter={1},value={2}",
                typeof(CommonClass), oParameter.GetType(), oParameter);
        }

 

泛型方法

 public static void Show<T>(T tParameter)//Show`1 声明方法是不知道参数类型,用占位符的形式代替泛型方法
{
    Console.WriteLine("This is {0}'s Show<T>,parameter={1},value={2}",
         typeof(GenericClass), tParameter.GetType(), tParameter);
}

 public static void Show(int iParameter)
 {
    Console.WriteLine("在没有指定泛型方法的时候,如果参数类型能匹配普通方法,都是调用的普通方法");
 }

 

泛型方法调用

   Console.WriteLine("泛型学习");
   Console.WriteLine(typeof(List<>));
   int iParameter = 506;
   long lParameter =789;
   string sParameter = "yoyo";

   object oParameter1 = 1264891326409324;//这里赋值为Int64的类型
   object oParameter2 = new People()
   {
        Id = 550,
        Name = "DoDo"
   };

   {
         Console.WriteLine("***************************泛型方式************************");
         GenericClass.Show<object >(oParameter1);
         GenericClass.Show<object >(oParameter2);
         //GenericClass.Show<int>(lParameter);//指定类型必须和参数一致
         GenericClass.Show(lParameter);//不指定,由编译器自动推算
         GenericClass.Show(iParameter);//在没有指定泛型方法的时候,如果参数类型能匹配普通方法,都是调用的普通方法
         GenericClass.Show<int>(iParameter);
         GenericClass.Show<string >(sParameter);
         Console.WriteLine();
    }

 

posted @ 2016-12-28 15:52  HepburnXiao  阅读(153)  评论(0编辑  收藏  举报