-
Notifications
You must be signed in to change notification settings - Fork 1
Method
Koson Trachu edited this page Aug 24, 2016
·
1 revision
#Method หน้าที่หลักของ method คือ ทำงานอะไรสักอย่าง แต่โดยส่วนใหญ่ method ที่สมบูรณ์จะประกอบด้วย
- ส่วนรับข้อมูล
- ส่วนส่งข้อมูลกลับ
- ส่วนประมวลผลข้อมูล
ตัวอย่าง method ในภาษา C#
int add (int a, int b)
{
int result = a + b;
return result;
}##Modifiers สําหรับ method
| ชนิดของ modifier | คีย์เวิร์ด |
|---|---|
| Static | static |
| Access | public, internal, private และ protected |
| Inheritance | new, virtual, abstract, override และ sealed |
| Partial method | partial |
| Unmanaged code | unsafe และ extern |
##Method Overloading เราสามารถใช้ชื่อ method ซ้ำกันได้ โดยที่ต้องมีชนิด และ/หรือ จํานวนพารามิเตอร์ที่แตกต่างกัน
void Foo(int x) {...}
void Foo(double x) {...}
void Foo(int x, float y) {...}
void Foo(float x, int y) {...}method ที่ชื่อ Foo ด้านบน จะมองว่าเป็นคนละ method กัน
เมื่อคอมไพเลอร์ทำงาน มันจะสร้าง method ที่มี signature ที่ต่างกันแลัวนำไปเก็บไว้ในรายการ overloading เพื่อที่จะเรียกใช้งานให้ถูกต้องตาม signature ที่ผู้เขียนโปรแกรมเรียกใช้
###ตัวอย่างการ oveload ที่ไม่ถูกต้อง
- ชนิด return ต่างกันแต่รายการ parameters เหมือนกัน
void Foo(int x) {...}
float Foo(double x) {...} // จะ error ตอนคอมไพล์- ชนิด parameters เหมือนกัน ต่างแค่เพียง modifier ของ parameter
void Goo(int[] x) {...}
void Goo(params int[] x) {...} // จะ error ตอนคอมไพล์- Pass-by-value versus pass-by-reference
void Foo(int x) {...}
void Foo(ref int x) {...} // OK
void Foo(out int x) {...} // จะ error ตอนคอมไพล์