Книга: C# 2008 Programmer
Implementing an Interface
Implementing an Interface
Once an interface is defined, you can create a new class to implement it. The class that implements that particular interface must provide all the implementation for the members defined in that interface.
For example, here's an Employee
class that implements the IPerson
interface:
public class Employee : IPerson {
public string Name { get; set; }
public DateTime DateofBirth { get; set; }
public ushort Age() {
return (ushort)(DateTime.Now.Year - this.DateofBirth.Year);
}
}
To implement an interface, you define your class and add a colon (:
) followed by the interface name:
public class Employee : IPerson
You then provide the implementation for the various members:
{
public string Name { get; set; }
public DateTime DateofBirth { get; set; }
public ushort Age() {
return (ushort)(DateTime.Now.Year - this.DateofBirth.Year);
}
Notice that I'm using the new automatic properties feature (discussed in Chapter 4) in C# 3.0 to implement the Name
and DateofBirthproperties
. That's why the implementation looks the same as the declaration in the interface.
As explained, all implemented members must have the public
access modifiers.
You can now use the class as you would a normal class:
Employee e1 = new Employee();
e1.DateofBirth = new DateTime(1980, 7, 28);
el.Name = "Janet";
Console.WriteLine(e1.Age()); //---prints out 28---
This could be rewritten using the new object initializer feature (also discussed in Chapter 4) in C# 3.0:
Employee el = new Employee() {
DateofBirth = new DateTime(1980, 7, 28),
Name = "Janet"
};
Console.WriteLine(e1.Age()); //---prints out 28---
- Chapter 5 Interfaces
- Defining an Interface
- Implementing Multiple Interfaces
- Extending Interfaces
- Interface Casting
- The is and as Operators
- Overriding Interface Implementations
- Generic Interfaces
- Collections Interfaces
- Implementing IEnumerable and IEnumerator
- Implementing WCF Callbacks
- Chapter 9 Plug and Play Implementation