Книга: C# 2008 Programmer

Defining an Interface

Defining an Interface

Defining an interface is similar to defining a class — you use the interface keyword followed by an identifier (the name of the interface) and then specify the interface body. For example:

interface IPerson {
 string Name { get; set; }
 DateTime DateofBirth { get; set; }
 ushort Age();

Here you define the IPerson interface containing three members — two properties and one function. You do not use any access modifiers on interface members — they are implicitly public. That's because the real use of an interface is to define the publicly accessible members (such as methods and properties) of a class so that all implementing classes have the same public members. The implementation of each individual member is left to the implementing class.

The declaration for the Name property consists simply of getand set accessors without implementation:

string Name { get; set; }

And the Age() method simply contains its return type (and input parameters, if any) but without its implementation:

ushort Age();

It's important to note that you cannot create an instance of the interface directly; you can only instantiate a class that implements that interface:

IPerson person = new IPerson();

Interface Naming Convention

By convention, begin the name of an interface with a capital I (such as IPerson, IManager, IEmployee, and so on) so that it is clear that you are dealing with an interface.

Оглавление книги

Генерация: 0.910. Запросов К БД/Cache: 3 / 0
Вверх Вниз