例一
using System;
namespace IspExample
{
class Program
{
static void Main(string[] args)
{
Driver driver = new Driver(new HeavyTank());
driver.Drive();
}
}
class Driver
{
private IVehicle vehicle;
public Driver(IVehicle vehicle)
{
this.vehicle = vehicle;
}
public void Drive()
{
vehicle.Run();
}
}
interface IVehicle
{
void Run();
}
interface IWeapon
{
void Fire();
}
interface ITank:IVehicle,IWeapon//接口隔离原则
{
}
class Car : IVehicle
{
public void Run()
{
Console.WriteLine("Car is Running!");
}
}
class HeavyTank : ITank
{
public void Fire()
{
Console.WriteLine("Fire! Fire!");
}
public void Run()
{
Console.WriteLine("Heavy tank is running!");
}
}
}
例二、显示实现接口
using System;
namespace IspExample
{
class Program
{
static void Main(string[] args)
{
var wk = new WarmKiller();
wk.Love();
(wk as IKiller).Kill();
}
}
interface IGentleman
{
void Love();
}
interface IKiller
{
void Kill();
}
class WarmKiller : IGentleman, IKiller
{
public void Love()
{
Console.WriteLine("I will love you for ever ...");
}
//显示实现所有成员
void IKiller.Kill()
{
Console.WriteLine("Let me kill the enemy ...");
}
}
}