泛型编程

理论点:

声明一个具体的泛型类时,编译器会至少做一个全面的字面上的类型替换,将T替换成具体的类型参数。不仅是字面上的替换,还包括全面的语义上的替换,做类型检查,检查T是否为有效的指定类型。

如何使用:

1. 普通方法与泛型方法

// 普通方法
static void Swap(ref string a, ref string b)
{
      T c = a;
      a = b;
      b = c;
}

// 泛型方法
static void Swap<T>(ref T a, ref T b)
{
      T c = a;
      a = b;
      b = c;
}

2. 泛型类的类型参数与内部泛型函数的类型参数不能相同。如果内部的泛型函数需要使用其他的类型参数,请考虑换一个标识符。

class GenericList<T>
{
    // CS0693
    void SampleMethod<T>() { }
}

class GenericList2<T>
{
    //No warning
    void SampleMethod<U>() { }
}

3. 对类型参数的约束

void SwapIfGreater<T>(ref T lhs, ref T rhs) where T : System.IComparable<T>
{
    T temp;
    if (lhs.CompareTo(rhs) > 0)
    {
        temp = lhs;
        lhs = rhs;
        rhs = temp;
    }
}

4. 泛型方法可以使用许多类型参数进行重载。 例如,下列方法可以全部位于同一个类中:

void DoWork() { }
void DoWork<T>() { }
void DoWork<T, U>() { }

5. 一个典型的泛型类示例

public class List<T> : IList<T>, ICollection<T>, IEnumerable<T>, IList, ICollection, IEnumerable
{

    public void CopyTo(T[] array);

    public int FindIndex(Predicate<T> match);

    public int IndexOf(T item);

    public void Sort(Comparison<T> comparison);

    public void Sort(IComparer<T> comparer);

}

参考文章:http://msdn.microsoft.com/zh-cn/library/vstudio/twcad0zb.aspx

原文地址:https://www.cnblogs.com/dirichlet/p/3280601.html