-
Notifications
You must be signed in to change notification settings - Fork 1
Properties
Koson Trachu edited this page Aug 24, 2016
·
1 revision
- เมื่อมองจากภายนอก properties จะเหมือนกับ fields
- แต่ถ้ามองจากภายใน มันจะทําหน้าที่เหมือนกับ method
- properties มีการ declare เหมือน fields
##Modifiers สําหรับ Properties
| ชนิดของ modifier | คีย์เวิร์ด |
|---|---|
| Static | static |
| Access | public, internal, private |
| Inheritance | new, virtual, abstract, override, sealed |
| Unmanaged code | unsafe, extern |
###ตัวอย่างการใช้งาน properties เปรียบเทียบกับ fields
public class Stock
{
decimal currentPrice; // private field เก็บข้อมูลอย่างเดียว ผู้ใช้จากภายนอกจะไม่เห็น
public decimal CurrentPrice // public properties ทำหน้าที่ติดต่อกับโลกภายนอก
{
get { return currentPrice;}
set { currentPrice = value;}
}
}
// get{ } และ set{ } เรียกว่า accessorจาก code ด้านบน สิ่งที่ผู้ใช้งานวัตถุจะมองเห็นจากภายนอก คือ
public class Stock
{
public decimal CurrentPrice;
}เวลานำไปใช้งาน สามารถกำหนดค่าหรือเรียกดูค่าจาก properties ได้เช่นเดียวกับ fields
static void Main()
{
Stock stock = new Stock();
stock.CurrentPrice = 12345; // คำสั่งนี้ เรียกใช้ setter ของ CurentPrice ในคลาส Stock
// นั้นคือ currentPrice = value;
var price = stock.CurrentPrice; // คำสั่งนี้ เรียกใช้ getter ของ CurentPrice ในคลาส Stock
// นั้นคือ return currentPrice;
}