方法的重載
- 方法重載:方法重載是指在同一個類中方法同名,參數不同(參數的類型、個數不同),調用時根據實參的形式,選擇與他匹配的方法執行操作的一種技術
- 參數個數和類型都⼀樣,但返回值類型不⼀樣,不能算做重載
方法的遞歸
- 方法自己調用自己
- 多個⽅法之間來回調⽤
- 使⽤遞歸時⼀定要有出口
- 示例:斐波那契數列
class MathTool
{
//斐波那契數列
//0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, …
public long GetFib(long index)
{
//如果編號小於1,則錯誤
if (index < 1)
{
return -1;
}
if (index == 1)
{
return 0;
}
if (index == 2)
{
return 1;
}
return GetFib(index - 1) + GetFib(index - 2);
}
}
class MainClass
{
public static void Main(string[] args)
{
MathTool ml = new MathTool();
long result = ml.GetFib(30);
Console.WriteLine(result);
}
}
得到結果