C#_泛型

  1. 泛型
    最近一直在写业务代码,由于公司的框架做了一次升级,写业务之余就去研究了一下,发现以往有些基础的知识点还不是很稳固,重新复习了一遍,这里写一下关于泛型的作用及使用方法。

当一个方法执行的功能全部相同,而参数的类型可能会不一样,此时需要定义多个方法包含不相类型的参数,此时由于方法的功能相同,就会产生代码冗余,如下代码:

  class Program
    {
        static void Main(string[] args)
        {
            
            MethodShow methodShow = new MethodShow();
            methodShow.showInt(3);
            methodShow.showString("hello");
           // methodShow.showString<string>("hello");   //上一行代码是调用泛型方法的简写
            Console.Read();
        }
    }
    public class MethodShow
    {
        /// <summary>
        /// int参数
        /// </summary>
        /// <param name="iParameter"></param>
        public void showInt(int iParameter)
        {
            Console.WriteLine("这里是MethodShow.showInt{0}类型为{1}",iParameter,iParameter.GetType());
        }
        /// <summary>
        /// string参数
        /// </summary>
        /// <param name="iParameter"></param>
        public void showString(string iParameter)
        {
            Console.WriteLine("这里是MethodShow.showString{0}类型为{1}", iParameter, iParameter.GetType());
        }
    }

使用泛型进行改造,代码如下:

class Program
    {
        static void Main(string[] args)
        {
            
            MethodShow methodShow = new MethodShow();
            methodShow.show(3);
            methodShow.show("hello");
            Console.Read();
        }
    }
    public class MethodShow
    {

        /// <summary>
        /// 泛型方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Parameter"></param>
        public void show<T> (T Parameter)
        {
            Console.WriteLine("这里是MethodShow.show{0}类型为{1}", Parameter, Parameter.GetType());
        }
    }

当然如果不使用泛型也可以实现改造那就是使得object类型作为参数的类型,object是所有类的基类,由于子类会继承父类所有子类可以替代父类,这个属于多态的特性,但是使用object时会产生拆箱装箱的操作会影响程序性能,还是用泛型吧,泛型还有其他优于object的地方,如下泛型约束:

    class Program
    {
        static void Main(string[] args)
        {
            Chines chines = new Chines
            {
                Id = 1,
                Name = "zhangxs",
                Age = 24,
                XiaongMao = "ttyy"
            };
           // MethodShow.SayHiShow<People>(chines);
              MethodShow.SayHiShow(chines);  //简写
            Console.Read();
        }
    }
    public class MethodShow
    {
   
        public static void SayHiShow<T>(T tParameter) where T : People
        {
            Console.WriteLine(tParameter.Age);
        }
    }
    public class People
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public void SayHi()
        {
            Console.WriteLine("{0}说",this.Name);
        }
    }
    public class Chines:People
    {
       public string XiaongMao { get; set; }
    }

当然约束还有很多,如下图所示

以上代码展示了使用泛型进行类型约束 , SayHiShow泛型方法后面加了where 指定了参数的类型必须是People或是它子类,否则会报错。

结束:泛型减速我们代码的冗余,使用约束保证了类型的安全性。

posted @ 2017-08-19 20:31  完美xtide  阅读(163)  评论(0编辑  收藏  举报