TOC

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

Classes:

Interfaces

Trong những chương trước chúng ta đã xem về lớp trừu tượng. Interface rất giống lớp trừu tượng và chúng cùng không có thể hiện. Tuy nhiên, interface thậm chí còn ở mức khái niệm hơn là lớp trừu tượng vì không hề có một phương thức nào được thực hiện. Vì vậy một interface là một lớp trừu tượng với các phương thức trừu tượng, và vì không có phương thức nào có mã nên không cần trường dữ liệu. Thuộc tính có thể có cũng như là indexer và event. Bạn có thể xem một interface là một contract- đó là một lớp mẫu để thực hiện toàn bộ phương thức và thuộc tính. Tuy nhiên, sự khác biệt quan trọng nhất là trong khi C# không cho phép đa thừa kế thì nó cho phép thực hiện nhiều interface!

Vì vậy, trong chương trình nó trông ra sao? Đây là một ví dụ hoàn chỉnh. Hãy nhìn xem, có lẽ bạn hãy thử và sau đó đọc mô tả cụ thể:

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!