方法多載 允許同一個類別中有多個方法擁有相同的名稱。多載方法彼此之間必須在下列其中一個方面有所不同:
方法多載不能以回傳型別為依據。
編譯器會根據參數的數量和型別,自動推斷要呼叫哪一個多載方法。
到目前為止,我們已經看到傳入方法的引數是依據位置與方法所宣告的參數配對。另一種做法是,特別是當常式需要大量引數時,呼叫端可以指定所宣告參數的識別碼來配對引數。
以下範例示範語法:
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!"
在這個練習中,你會和最要好的朋友一起玩一款名為「巫師與戰士」的角色扮演遊戲。你是遊戲主持人,負責讓遊戲世界在玩家眼前活起來。其中一個關鍵環節,就是把遊戲的種種描述給玩家聽:角色的狀態是什麼、他們造訪的城鎮長什麼樣子,等等。
你有 5 個任務,要把遊戲的各個部分描述給玩家聽喔。
每個角色都有職業、等級和生命值,描述方式為:"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."