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