Sdílet prostřednictvím


Obecná rozhraní (Průvodce programováním v C#)

Často je užitečné definovat rozhraní pro obecnou kolekci třídy nebo obecný tříd, které představují položky v kolekci.Předvoleb pro obecný třídy je obecné rozhraní použít jako IComparable namísto IComparable, aby se zabránilo boxing a na volné určení hodnoty typů operací.Na.NET Framework, knihovna tříd definuje několik obecné rozhraní pro použití s třídami v kolekci System.Collections.Generic oboru názvů.

Pokud je zadána jako omezení parametru typu, lze použít pouze pro typy, které implementují rozhraní.Následující kód zobrazuje příklad SortedList<T> třídy, který je odvozen od GenericList<T> třídy.Další informace naleznete v tématu Úvod do obecných typů (Průvodce programováním v C#).SortedList<T>Přidá omezení where T : IComparable<T>.To umožňuje BubbleSort metoda v SortedList<T> použití obecného CompareTo metodu na prvky seznamu.V tomto příkladu jsou prvky seznamu jednoduchou třídu Person, který implementuje IComparable<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");
    }
}

Více rozhraní lze zadat jako na jediný typ omezení:

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

Rozhraní lze definovat více než jeden parametr typu takto:

interface IDictionary<K, V>
{
}

Rozhraní také platí pravidla dědičnosti, které platí pro třídy:

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

Obecné rozhraní může dědit z obecné rozhraní, pokud je obecné rozhraní opravné položky k variantou, což znamená, že pouze vrácenou hodnotu používá jeho parametr typu.V.NET Framework, knihovna tříd, IEnumerable dědí z IEnumerable protože IEnumerable používá pouze T v vrácená hodnota GetEnumerator a Current vlastnost getter.

Konkrétní třídy lze implementovat rozhraní uzavřené vyrobeno, takto:

interface IBaseInterface<T> { }

class SampleClass : IBaseInterface<string> { }

Obecný třídy mohou implementovat obecný a uzavřené vyrobeno rozhraní jako parametr seznam tříd dodává všechny argumenty požadované rozhraní, takto:

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

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

Pravidla, která řídí, přetížení metody jsou stejné pro metody třídy obecný, obecný struktur nebo obecné rozhraní.Další informace naleznete v tématu Obecné metody (Průvodce programováním v C#).

Viz také

Referenční dokumentace

Úvod do obecných typů (Průvodce programováním v C#)

interface (Referenční dokumentace jazyka C#)

Koncepty

Průvodce programováním v C#

Další zdroje

Obecné typy v architektuře .NET Framework