Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

วิธีการสร้างเมธอดกำหนดเอง (Custom Method) ใน C#

ในการสร้างเมธอดกำหนดเองใน C# ให้ใช้ไวยากรณ์ดังนี้:

<Access Specifier> <Return Type> <Method Name>(Parameter List) { Method Body }

องค์ประกอบต่างๆ ของเมธอด:

  • Access Specifier - กำหนดความมองเห็นของตัวแปรหรือเมธอดจากคลาสอื่น
  • Return Type - เมธอดอาจส่งคืนค่าได้ หากไม่ส่งคืนค่าใดๆ ให้ใช้ void
  • Method Name - ตัวระบุที่ไม่ซ้ำกัน คำนึงถึงตัวพิมพ์เล็ก-ใหญ่
  • Parameter List - ใช้ส่งผ่านและรับข้อมูล อาจไม่มีพารามิเตอร์ก็ได้
  • Method Body - ชุดคำสั่งสำหรับทำกิจกรรมที่ต้องการ

ตัวอย่าง

ตัวอย่างเมธอด FindMax สำหรับหาค่าสูงสุดระหว่างสองจำนวน:

using System;

namespace Demo {
    class NumberManipulator {
        public int FindMax(int num1, int num2) {
            int result;
            if (num1 > num2)
                result = num1;
            else
                result = num2;
            return result;
        }

        static void Main(string[] args) {
            int a = 90;
            int b = 15;
            int ret;
            NumberManipulator n = new NumberManipulator();
            ret = n.FindMax(a, b);
            Console.WriteLine("Max value is : {0}", ret);
            Console.ReadLine();
        }
    }
}

ผลลัพธ์

Max value is : 90