C# 接口

■接口:使用關鍵字interface,只是定義一系列的行爲類型,不提供任何實現
interface IMovable{
    float speed{get;}
    float maxSpeed{get;set;}
    void Run();
    void Walk();
    void Fly();
}
■接口的實現,通過冒號來實現

<!--<br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /> http://www.CodeHighlighter.com/<br /> <br /> -->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();
        }
    }
}

結果:
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



一個類可以實現多個接口。如有兩個接口IMovable,ISpeakable,定義一個Person類來實現這兩個接口
class Person:IMovable,ISpeakable
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章