TOC

This article is currently in the process of being translated into Italian (~30% done).

Classi:

Interfaces

Nei precedenti capitoli, abbiamo visto le classi astratte. Le interfacce sono molto simili alle classi astratte e hanno in comune il fatto che non non si possono creare istanze. Comunque, le interfacce sono molto più concettuali delle classi astratte, dato che non è permesso nessun corpo all'interno del metodo. Quindi una interfaccia è una sorta di classe astratta ma con solo metodi astratti, e dato che non ci sono metodi con del codice, non c'è bisogno di nessun campo. Le proprietà sono permesse però, come lo sono gli indici e gli eventi. Puoi considerare una interfaccia come un contratto - la classe che la implementa dovrà implementare tutti i metodi e le proprietà. Comunque, la più importante differenza è che, mentre C# non ti permette la multi ereditarietà, dove le classi ereditano più di una classe base, la classe può implementare più di una interfaccia!

Quindi, che sembianze prende il codice? Ecco un esempio abbastanza completo. Guarda, forse provalo tu stesso, e poi continua a leggere per la spiegazione completa:

using System;
using System.Collections.Generic;

namespace Interfaces
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Dog> dogs = new List<Dog>();
            dogs.Add(new Dog("Fido"));
            dogs.Add(new Dog("Bob"));
            dogs.Add(new Dog("Adam"));
            dogs.Sort();
            foreach(Dog dog in dogs)
                Console.WriteLine(dog.Describe());
            Console.ReadKey();
        }
    }

    interface IAnimal
    {
        string Describe();

        string Name
        {
            get;
            set;
        }
    }

    class Dog : IAnimal, IComparable
    {
        private string name;

        public Dog(string name)
        {
            this.Name = name;
        }

        public string Describe()
        {
            return "Hello, I'm a dog and my name is " + this.Name;
        }

        public int CompareTo(object obj)
        {
            if(obj is IAnimal)
                return this.Name.CompareTo((obj as IAnimal).Name);
            return 0;
        }

        public string Name
        {
            get { return name; }
            set { name = value; }
        }
    }
}

Let's start in the middle, where we declare the interface. As you can see, the only difference from a class declaration, is the keyword used - interface instead of class. Also, the name of the interface is prefixed with an I for Interface - this is simply a coding standard, and not a requirement. You can call your interfaces whatever you want, but since they are used like classes so much that you might have a hard time telling the difference in some parts of your code, the I prefix makes pretty good sense.

Then we declare the Describe method, and afterwards, the Name property, which has both a get and a set keyword, making this a read and writeable property. You will also notice the lack of access modifiers (public, private, protected etc.), and that's because they are not allowed in an interface - they are all public by default.

Next up is our Dog class. Notice how it looks just like inheriting from another class, with the colon between the class name and the class/interface being subclassed/implemented. However, in this case, two interfaces are implemented for the same class, simply separated by a comma. You can implement as many interfaces as you want to, but in this case we only implement two - our own IAnimal interface, and the .NET IComparable interface, which is a shared interface for classes that can be sorted. Now as you can see, we have implemented both the method and the property from the IAnimal interface, as well as a CompareTo method from the IComparable interface.

Now you might be thinking: If we have to do all the work our self, by implementing the entire methods and properties, why even bother? And a very good example of why it's worth your time, is given in the top of our example. Here, we add a bunch of Dog objects to a list, and then we sort the list. And how does the list know how to sort dogs? Because our Dog class has a CompareTo method that can tell how to compare two dogs. And how does the list know that our Dog object can do just that, and which method to call to get the dogs compared? Because we told it so, by implementing an interface that promises a CompareTo method! This is the real beauty of interfaces.

This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!