_方法重载_允许同一个类中的多个方法使用相同的名称。重载的方法之间必须在以下某一方面有所不同:
不能根据返回类型进行方法重载。
编译器会根据形参的数量和类型,自动推断该调用哪个重载方法。
到目前为止,我们看到传入方法的实参是按位置与方法声明的形参相匹配的。还有一种方式:当例程需要大量实参时,调用方可以通过指定所声明形参的标识符来匹配实参。
下面的代码演示了这种语法:
class Card
{
static string NewYear(int year, int month, int day)
{
return $"Happy {year}-{month}-{day}!";
}
}
Card.NewYear(month: 1, day: 1, year: 2020); // => "Happy 2020-1-1!"
为方法的形参指定默认值,就能把它设为可选形参。调用带可选形参的方法时,调用方不必为它们传值。如果没有为可选形参传值,就会使用它的默认值。
可选形参_必须_位于形参列表的末尾;它们后面不能再跟非可选形参。
class Card
{
static string NewYear(int year = 2020)
{
return $"Happy {year}!";
}
}
Card.NewYear(); // => "Happy 2020!"
Card.NewYear(1999); // => "Happy 1999!"
在这个练习中,你要和最好的朋友们一起玩一款名为“Wizard and Warriors”的角色扮演游戏。你是游戏主持人,负责让游戏世界在玩家眼前活起来。其中很关键的一点,就是向玩家描述游戏内容:角色的状态如何、他们正在造访的城镇长什么样,等等。
你有五个任务,需要向玩家描述游戏的不同部分。
每个角色都有职业、等级和生命值,其描述格式为:"You're a level <LEVEL> <CLASS> with <HIT_POINTS> hit points."。实现(静态)GameMaster.Describe 方法,它接受一个 Character 作为唯一参数,并返回对应的描述。
var character = new Character();
character.Class = "Wizard";
character.Level = 4;
character.HitPoints = 28;
GameMaster.Describe(character);
// => "You're a level 4 Wizard with 28 hit points."
每个目的地都有名称和居民数量,其描述格式为:"You've arrived at <NAME>, which has <INHABITANTS> inhabitants."。实现(静态)GameMaster.Describe 方法,它接受一个 Destination 作为唯一参数,并返回对应的描述。
var destination = new Destination();
destination.Name = "Muros";
destination.Inhabitants = 732;
GameMaster.Describe(destination);
// => "You've arrived at Muros, which has 732 inhabitants."
角色可以使用以下两种方式之一前往目的地:
"You're traveling to your destination by walking."
"You're traveling to your destination on horseback."
实现(静态)GameMaster.Describe 方法,它接受一个 TravelMethod 作为唯一参数,并返回对应的描述。
GameMaster.Describe(TravelMethod.Horseback);
// => "You're traveling to your destination on horseback."
当角色前往某个目的地时,描述由各个单独的描述组合而成:"<CHARACTER> <TRAVEL_METHOD> <DESTINATION>"。实现(静态)GameMaster.Describe 方法,它接受一个 Character、一个 Destination 和一个 TravelMethod 作为参数,并返回对应的描述。
var character = new Character();
character.Class = "Wizard";
character.Level = 4;
character.HitPoints = 28;
var destination = new Destination();
destination.Name = "Muros";
destination.Inhabitants = 732;
GameMaster.Describe(character, destination, TravelMethod.Horseback);
// => "You're a level 4 Wizard with 28 hit points. You're traveling to your destination on horseback. You've arrived at Muros, which has 732 inhabitants."
大多数情况下,角色都是步行前往目的地的。为了方便,玩家可以省略出行方式,此时会默认出行方式是步行。实现(静态)GameMaster.Describe 方法,它接受一个 Character 和一个 Destination 作为参数,并返回对应的描述。
var character = new Character();
character.Class = "Wizard";
character.Level = 4;
character.HitPoints = 28;
var destination = new Destination();
destination.Name = "Muros";
destination.Inhabitants = 732;
GameMaster.Describe(character, destination);
// => "You're a level 4 Wizard with 28 hit points. You're traveling to your destination by walking. You've arrived at Muros, which has 732 inhabitants."