สำนักวิทยบริการและเทคโนโลยีสารสนเทศ (สวส.)

Office of Academic Resources and Information Technology


Office of Academic Resources and Information Technology

Value Types (3) : Enumerations

Value Types (3) : Enumerations

 
Enumerations หรือ Sealed value types คือ กลุ่มของค่าคงที่ที่เรากำหนดขึ้นเอง ซึ่งกลุ่มของค่าคงที่เหล่านี้มักจะเป็นข้อมูลที่เกี่ยวข้องกัน และค่าคงที่เหล่านี้จะมีค่าเป็นตัวเลขกำกับไว้ด้วย หรือพูดง่ายๆ ว่ามันคือ (string) Array ในแบบ value type นั้นเองครับ (ปกติ Array ใน java หรือ .net จะเป็น object) ตัวเลขที่กำกับไว้ ก็เปรียบกับ index ใน array ครับ

ประโยชน์ของ Enumerations คือ
  • ทำให้โค้ดอ่านง่ายขึ้น (readability) ซึ่งทำให้ดูแลรักษาโค้ดง่ายด้วย (maintain)
  • ทำให้ลดการ hard coding ได้ (hard coding หรือ hard code คือ การฝังค่าข้อมูลลงใน source code เลยซึ่งถือเป็นการเขียนโปรแกรมที่ไม่เป็นระเบียบในระหว่างพัฒนา แต่อาจจะมีประโยชน์ในขั้นตอนทดสอบระบบ)
  • บางกรณีที่ใช้แทน array จะสามารถเพิ่มประสิทธิภาพ (performance) ให้กับซอฟต์แวร์ที่เขียนได้
การประกาศ Enumeration สำหรับ VB.NET (Enumeration Declaration for VB.NET)
|<attributes>| |<modifiers>| Enum <identifier> |As <data>|
<enumerator-list> |= <number>| |:|
End Enum

การประกาศ Enumeration สำหรับ C# (Enumeration Declaration for C#)
|<attributes>| |<modifiers>| enum <identifier> |: <data>|
{
<enumerator-list> |= <number>| |,|
}

ความหมาย
ในเครื่องหมาย | หมายถึง มีหรือไม่มีก็ได้
attributes คือ แท็กซึ่งใช้สำหรับปรับแต่งความสามารถ
modifiers ได้แก่ Private, Friend, Public ส่วน Protected และ Protected Friend ไม่สามารถใช้ใน Module ได้
identifier คือ ชื่อที่จะตั้งให้ enum
data type ได้แก่ type ที่เป็นตัวเลขจำนวนเต็มทั้งหลาย ได้แก่ Byte, Integer, Long, SByte, Short, UInteger, ULong, UShort ถ้าไม่ระบุจะถือเป็น Integer

ตัวอย่าง

'VB.NET
Enum MemberStatus
Active
Inactive
Expire
Close
End Enum

Public Enum Result As Integer
Excellent = 2
Good = 1
Average = 0
Fair = -1
Poor = -2
End Enum

<Serializable()> Protected Friend Enum ColorCode As Byte
Red = 100 : Green = 51 : Blue = 255
End Enum

//C#
enum MemberStatus
{
Active,
Inactive,
Expire,
Close
}

public enum Result : int
{
Excellent = 2
Good = 1
Average = 0
Fair = -1
Poor = -2
}

[Serializable]
protected internal enum ColorCode : byte
{
Red = 100, Green = 51, Blue = 255
}


แหล่งข้อมูล :
Enum Statement (Visual Basic)
Enumerations in VB.NET (ASP Alliance)