■接口:使用關(guān)鍵字interface,只是定義一系列的行為類型,不提供任何實現(xiàn)
interface IMovable{
float speed{get;}
float maxSpeed{get;set;}
void Run();
void Walk();
void Fly();
}
■接口的實現(xiàn),通過冒號來實現(xiàn)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace useInterface
{
interface IMovable {
float Speed{get;}
float MaxSpeed { get; set; }
void Run();
void Walk();
void Fly();
}
class Dog : IMovable {
public float Speed {
get {
return 10.5f;
}
}
private float _MaxSpeed;
public float MaxSpeed{
get { return this._MaxSpeed; }
set { this._MaxSpeed = value; }
}
public void Run() {
System.Console.WriteLine("Dog is running");
}
public void Walk()
{
System.Console.WriteLine("Dog is walking");
}
public void Fly()
{
System.Console.WriteLine("Dog can't fly");
}
}
class Person : IMovable
{
public float Speed
{
get
{
return 20.5f;
}
}
private float _MaxSpeed;
public float MaxSpeed
{
get { return this._MaxSpeed; }
set { this._MaxSpeed = value; }
}
public void Run()
{
System.Console.WriteLine("Person is running");
}
public void Walk()
{
System.Console.WriteLine("Person is walking");
}
public void Fly()
{
System.Console.WriteLine("Person flies with a plane");
}
}
class Program
{
static void SthMove(IMovable mov) {
string type = mov.GetType().Name;
System.Console.WriteLine("This is a {0} ",type);
System.Console.WriteLine("{0}.Speed={1}",type,mov.Speed);
System.Console.WriteLine("{0}.MaxSpeed={1}", type, mov.MaxSpeed);
mov.Walk();
mov.Run();
mov.Fly();
}
static void Main(string[] args)
{
Person aPerson = new Person();
aPerson.MaxSpeed = 50;
SthMove(aPerson);
IMovable mov = new Dog();
mov.MaxSpeed = 20;
SthMove(mov);
System.Console.ReadLine();
}
}
}
結(jié)果:
This is a Person
Person.Speed=20.5
Person.MaxSpeed=50
Person is walking
Person is running
Person flies with a plane
This is a Dog
Dog.Speed=10.5
Dog.MaxSpeed=20
Dog is walking
Dog is running
Dog can't fly
一個類可以實現(xiàn)多個接口。如有兩個接口IMovable,ISpeakable,定義一個Person類來實現(xiàn)這兩個接口
class Person:IMovable,ISpeakable
posted on 2009-10-26 18:21
期待明天 閱讀(260)
評論(0) 編輯 收藏 所屬分類:
CSharp