C#泛型

1、泛型的概念

  通过“参数化类型”来实现在同一份代码上操作多种数据类型。利用“参数化类型”将类型抽象化,从而实现灵活的复用。

2、常用到的泛型

  泛型类、泛型方法、泛型接口、泛型委托等。

3、注意事项

  (1)C#泛型要求对“所有泛型类型或泛型方法的类型参数”的任何假定,都要基于“显式的约束”,以维护 C#所要求的类型安全。

  (2)“显式约束”由 where 子句表达,可以指定“基类约束”,“接口约束”,“构造器约束”“值类型/引用类型约束”共四种约束。

  (3)“显式约束”并非必须,如果没有指定“显式约束”,泛型类型参数将只能访问 System.Object 类型中的公有方法。

4、泛型优点

  (1)减少代码重复,可读性高,易于维护。(2)扩展性好,灵活度高。(3)避免隐式的装箱拆箱,提高程序运行速度。(参考

5、简单例子

  如下,分别使用普通类和泛型类获取不同类型数组的最大值。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GenericDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] arrInt = new int[] { 1, 2, 3, 2, 1 };
            string[] arrStr = new string[] { "a", "b", "c", "b", "a"};

            /****不使用泛型****/
            MyClass a = new MyClass();
            a.GetMax(arrInt);
            a.GetMax(arrStr);
            /****不使用泛型****/

            /****使用泛型****/
            MyClass<int> b = new MyClass<int>();
            b.GetMax(arrInt);
            MyClass<string> c = new MyClass<string>();
            c.GetMax(arrStr);
            /****使用泛型****/

            Console.Read();
        }
    }

    /// <summary>
    /// 不使用泛型
    /// </summary>
    public class MyClass
    {
        //方法参数类型不同,需要写多个方法,有改动处不易维护。
        public void GetMax(int[] arr)
        {
            Console.WriteLine(arr.Max());
        }
        public void GetMax(string[] arr)
        {
            Console.WriteLine(arr.Max());
        }
    }

    /// <summary>
    /// 使用泛型
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class MyClass<T> where T : IComparable //接口约束
    {
        //只此一个方法即可,易读性高,且易维护.
        public void GetMax(T[] arr)
        {
            Console.WriteLine(arr.Max());
        }
    }
}