หากต้องการเรียกใช้เมธอด C# แบบเรียกซ้ำ คุณสามารถลองเรียกใช้โค้ดต่อไปนี้ ในที่นี้ แฟกทอเรียลของตัวเลขคือสิ่งที่เรากำลังค้นหาโดยใช้ฟังก์ชันแบบเรียกซ้ำ display()
หากค่าเป็น 1 จะส่งกลับ 1 เนื่องจากแฟคทอเรียลเป็น 1
if (n == 1) return 1;
ถ้าไม่เช่นนั้น ฟังก์ชันแบบเรียกซ้ำจะถูกเรียกสำหรับการวนซ้ำต่อไปนี้ หาก 1 คุณต้องการค่าเป็น 5!
Interation1: 5 * display(5 - 1); Interation2: 4 * display(4 - 1); Interation3: 3 * display(3 - 1); Interation4: 4 * display(2 - 1);>
ต่อไปนี้คือโค้ดที่สมบูรณ์สำหรับเรียกใช้เมธอด C# แบบเรียกซ้ำ
ตัวอย่าง
using System;
namespace MyApplication {
class Factorial {
public int display(int n) {
if (n == 1)
return 1;
else
return n * display(n - 1);
}
static void Main(string[] args) {
int value = 5;
int ret;
Factorial fact = new Factorial();
ret = fact.display(value);
Console.WriteLine("Value is : {0}", ret );
Console.ReadLine();
}
}
} ผลลัพธ์
Value is : 120