public class Skyscraper
{
Story[] stories;
public Story this [int index]
{
get { return stories [index]; }
set
{
if (value != null)
{
stories [index] = value;
}
}
}
//...
}
Skyscraper empireState = new Skyscraper (/*...*/);
empireState [102] = new Story ("The Top One", /*...*/);
// 产生事件的类
public class Game
{
// 注意使用关键字
public event ScoreChangeEventHandler ScoreChange;
int score;
// 属性Score
public int Score
{
get { return score; }
set
{
if (score != value)
{
bool cancel = false;
ScoreChange (value, ref cancel);
if (! cancel)
score = value;
}
}
}
}
// 处理事件的类
public class Referee
{
public Referee (Game game)
{
// 监视game中的score的分数改变
game.ScoreChange += new ScoreChangeEventHandler (game_ScoreChange);
}
// 注意这个方法签名和ScoreChangeEventHandler的方法签名要匹配
private void game_ScoreChange (int newScore, ref bool cancel)
{
if (newScore < 100)
System.Console.WriteLine ("Good Score");
else
{
cancel = true;
System.Console.WriteLine ("No Score can be that high!");
}
}
}
// 测试类
public class GameTest
{
public static void Main ()
{
Game game = new Game ();
Referee referee = new Referee (game);
game.Score = 70; // 译注:输出 Good Score
game.Score = 110; // 译注:输出 No Score can be that high!
}
}
public class Direction
{
public final static int NORTH = 1;
public final static int EAST = 2;
public final static int WEST = 3;
public final static int SOUTH = 4;
}