共用方式為


泛型介面 (C# 程式設計手冊)

通常為泛型集合類別或代表集合中項目的泛型類別定義介面是很有用的。泛型類別最好是使用泛型介面,例如 IComparable<T>,而非 IComparable,如此才能避免實值型別 (Value Type) 的 boxing 和 unboxing 作業。.NET Framework 類別庫 (Class Library) 定義了幾種泛型介面,以便搭配 System.Collections.Generic 命名空間 (Namespace) 中的集合類別使用。

當介面指定當做型別參數上的條件約束時,就只能使用實作介面的型別。下列程式碼範例示範衍生自 GenericList<T> 類別的 SortedList<T> 類別。如需詳細資訊,請參閱 泛型簡介 (C# 程式設計手冊)。SortedList<T> 會加入條件約束 where T : IComparable<T>。如此可讓 SortedList<T> 中的 BubbleSort 方法使用清單項目上的泛型 CompareTo 方法。在這個程式碼範例中,清單項目是實作 IComparable<Person> 的簡單類別 Person。

//Type parameter T in angle brackets.
public class GenericList<T> : System.Collections.Generic.IEnumerable<T>
{
    protected Node head;
    protected Node current = null;

    // Nested class is also generic on T
    protected class Node
    {
        public Node next;
        private T data;  //T as private member datatype

        public Node(T t)  //T used in non-generic constructor
        {
            next = null;
            data = t;
        }

        public Node Next
        {
            get { return next; }
            set { next = value; }
        }

        public T Data  //T as return type of property
        {
            get { return data; }
            set { data = value; }
        }
    }

    public GenericList()  //constructor
    {
        head = null;
    }

    public void AddHead(T t)  //T as method parameter type
    {
        Node n = new Node(t);
        n.Next = head;
        head = n;
    }

    // Implementation of the iterator
    public System.Collections.Generic.IEnumerator<T> GetEnumerator()
    {
        Node current = head;
        while (current != null)
        {
            yield return current.Data;
            current = current.Next;
        }
    }

    // IEnumerable<T> inherits from IEnumerable, therefore this class 
    // must implement both the generic and non-generic versions of 
    // GetEnumerator. In most cases, the non-generic method can 
    // simply call the generic method.
    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

public class SortedList<T> : GenericList<T> where T : System.IComparable<T>
{
    // A simple, unoptimized sort algorithm that 
    // orders list elements from lowest to highest:

    public void BubbleSort()
    {
        if (null == head || null == head.Next)
        {
            return;
        }
        bool swapped;

        do
        {
            Node previous = null;
            Node current = head;
            swapped = false;

            while (current.next != null)
            {
                //  Because we need to call this method, the SortedList
                //  class is constrained on IEnumerable<T>
                if (current.Data.CompareTo(current.next.Data) > 0)
                {
                    Node tmp = current.next;
                    current.next = current.next.next;
                    tmp.next = current;

                    if (previous == null)
                    {
                        head = tmp;
                    }
                    else
                    {
                        previous.next = tmp;
                    }
                    previous = tmp;
                    swapped = true;
                }
                else
                {
                    previous = current;
                    current = current.next;
                }
            }
        } while (swapped);
    }
}

// A simple class that implements IComparable<T> using itself as the 
// type argument. This is a common design pattern in objects that 
// are stored in generic lists.
public class Person : System.IComparable<Person>
{
    string name;
    int age;

    public Person(string s, int i)
    {
        name = s;
        age = i;
    }

    // This will cause list elements to be sorted on age values.
    public int CompareTo(Person p)
    {
        return age - p.age;
    }

    public override string ToString()
    {
        return name + ":" + age;
    }

    // Must implement Equals.
    public bool Equals(Person p)
    {
        return (this.age == p.age);
    }
}

class Program
{
    static void Main()
    {
        //Declare and instantiate a new generic SortedList class.
        //Person is the type argument.
        SortedList<Person> list = new SortedList<Person>();

        //Create name and age values to initialize Person objects.
        string[] names = new string[] 
        { 
            "Franscoise", 
            "Bill", 
            "Li", 
            "Sandra", 
            "Gunnar", 
            "Alok", 
            "Hiroyuki", 
            "Maria", 
            "Alessandro", 
            "Raul" 
        };

        int[] ages = new int[] { 45, 19, 28, 23, 18, 9, 108, 72, 30, 35 };

        //Populate the list.
        for (int x = 0; x < 10; x++)
        {
            list.AddHead(new Person(names[x], ages[x]));
        }

        //Print out unsorted list.
        foreach (Person p in list)
        {
            System.Console.WriteLine(p.ToString());
        }
        System.Console.WriteLine("Done with unsorted list");

        //Sort the list.
        list.BubbleSort();

        //Print out sorted list.
        foreach (Person p in list)
        {
            System.Console.WriteLine(p.ToString());
        }
        System.Console.WriteLine("Done with sorted list");
    }
}

在單一型別上可以指定多個介面當做條件約束,如下所示:

class Stack<T> where T : System.IComparable<T>, IEnumerable<T>
{
}

一個介面可以定義一個以上的型別參數,如下所示:

interface IDictionary<K, V>
{
}

適用於類別的繼承 (Inheritance) 規則也適用於介面:

interface IMonth<T> { }

interface IJanuary     : IMonth<int> { }  //No error
interface IFebruary<T> : IMonth<int> { }  //No error
interface IMarch<T>    : IMonth<T> { }    //No error
//interface IApril<T>  : IMonth<T, U> {}  //Error

如果泛型介面是 contra-variant (表示只會使用其型別參數當做傳回值) 時,泛型介面就可以繼承自非泛型介面。在 .NET Framework 類別庫中,因為 IEnumerable<T> 只會在 GetEnumerator 的傳回值和 Current 屬性 getter 中使用 T,所以 IEnumerable<T> 會繼承自 IEnumerable

具象類別可以實作封閉式建構的介面,如下所示:

interface IBaseInterface<T> { }

class SampleClass : IBaseInterface<string> { }

只要類別參數清單提供介面所需的全部引數,泛型類別就可以實作泛型介面或封閉式建構的介面,如下所示:

interface IBaseInterface1<T> { }
interface IBaseInterface2<T, U> { }

class SampleClass1<T> : IBaseInterface1<T> { }          //No error
class SampleClass2<T> : IBaseInterface2<T, string> { }  //No error

控制方法多載的規則與泛型類別、泛型結構 (Struct) 或泛型介面中的方法相同。如需詳細資訊,請參閱 泛型方法 (C# 程式設計手冊)

請參閱

參考

泛型簡介 (C# 程式設計手冊)

interface (C# 參考)

概念

C# 程式設計手冊

其他資源

.NET Framework 中的泛型