Книга: 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:
//---error---
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.
- Chapter 5 Interfaces
- Defining a Class
- Interface Casting
- Interfacing with Other Languages
- Chapter 15. Graphical User Interfaces for Iptables
- Displaying Interface Statistics
- QueryInterface и IUnknown
- 5.1.2. The Directory Server Interface
- Command-Line Network Interface Configuration
- Laying the Foundation: The localhost Interface
- Checking for the Availability of the Loopback Interface
- Configuring the Loopback Interface Manually