1 介面的定義public interface IAttribute
{
string Name { get;set;}
}
public class Component : IAttribute
{
public string Name
{
get
{
return "張三";
}
set
{
this.Name = value;
}
}
}
2 介面的實現public interface IPlayer
{
string GetName();
string Show();
}
public class Options
{
public static readonly string JIANDAO = "剪刀";
public static readonly string SHITOU = "石頭";
public static readonly string BU = "布";
}
public class Grandpa:IPlayer
{
public string GetName()
{
return "爺爺";
}
public string Show()
{
Random random = new Random();
int i = (int)(random.Next() * 1000) % 3;
switch (i)
{
case 0: return Options.JIANDAO;
case 1: return Options.SHITOU;
default: return Options.BU;
}
}
}
public class Grandson:IPlayer
{
public string GetName()
{
return "孫子";
}
public string Show()
{
return Options.JIANDAO;
}
}
3. 介面的繼承
一個介面可從一個或多個基底介面繼承
interface IA { }
interface IB:IA { }
interface IC : IA, IB { }
interface ID : IA, IB, IC { }
4.介面與回調
static void Main(string[] args)
{
//建立一個控制器對象,將提供給它的回調對象傳入
Resolve resolve = new Resolve(new PlayBasketball());
resolve.Play();
resolve = new Resolve(new PlayFootball());
resolve.Play();
}
public interface IPlayer
{
void Play();
}
public class PlayBasketball:IPlayer
{
public void Play()
{
Console.WriteLine("玩籃球");
}
}
public class PlayFootball : IPlayer
{
public void Play()
{
Console.WriteLine("玩足球");
}
}
/// 控制角色--控制器對象
/// </summary>
public class Resolve
{
//持有一個介面的引用,通過構造方法初始化
private IPlayer player;
public Resolve(IPlayer player)
{
this.player = player;
}
public void Play()
{
player.Play();
}
}
來自:http://www.cnblogs.com/beniao/archive/2008/07/28/1249031.html