Enumeration in C#
กัญจน์ จรัสโรจนพร 650710213
การประกาศตัวแปร Enumeration
Enumeration (หรืออีกชื่อ enum) เป็น value data type ในภาษา C#. ซึ่งใช้ในการสร้างกลุ่มของค่าคงที่ที่เกี่ยวข้องกันภายใต้ชื่อเดียวกัน การใช้ enum ทำให้โค้ดอ่านง่ายและจัดการกับข้อมูลที่มีตัวเลือกจำกัดได้สะดวกขึ้น. Enumeration สามารถถูกได้ประกาศด้วย enum
แล้วตามด้วยชื่อที่เราต้องการ แล้วข้อมูลสมาชิกก็จะใส่ข้างใน {} โดยการใส่ ; เพื่อแยกแต่ละข้อมูล
// C# program to illustrate the enums
// with their default values
using System;
namespace ConsoleApplication1 {
// making an enumerator 'month'
enum month
{
// following are the data members
jan,
feb,
mar,
apr,
may
}
class Program {
// Main Method
static void Main(string[] args)
{
// getting the integer values of data members..
Console.WriteLine("The value of jan in month " +
"enum is " + (int)month.jan);
}
}
}
ค่าสมาชิกของ Enumeration
โดยดั้งเดิม ค่าเริ่มของสมาชิก Enumeration จะเป็น int
เริ่มที่ 0 แล้วตัวถัดๆไปเลขก็จะเพิ่มขึ้นจากตัวก่อน 1 แล้วเราสามารถกำหนดสมาชิกของ Enumeration ให้เป็นค่าดังที่เราต้องการ และกระทำการดังกล่าวจะทำให้ค่าถัดๆไปถูกเพิ่มตามลำดับทั่วไป
enum Months
{
January, // 0
February, // 1
March=5, // 5
April, // 6
May, // 7
June, // 8
November=May+4, // 11
December // 12
}
static void Main(string[] args)
{
int myNum1 = (int) Months.April;
Console.WriteLine(myNum1);
int myNum2 = (int) Months.November;
Console.WriteLine(myNum2);
}
output
6
11
การกำหนดชนิดข้อมูลสมาชิกของ Enumeration
โดยปกติ ชนิดข้อมูลสมาชิกของ Enumeration ในภาษา C# จะเป็น Int แต่เราก็สามารถเปลี่ยนเป็นชนิดข้อมูลอื่นได้ เช่น byte, sbyte, short, ushort, int, uint, long, ulong (จำพวกทศนิยม และ bool จะใช้ไม่ได้)
// C# program to illustrate the changing
// of data type of enum members
using System;
namespace ConsoleApplication4 {
// changing the type to byte using :
enum Button : byte {
// OFF denotes the Button is
// switched Off... with value 0
OFF,
// ON denotes the Button is
// switched on.. with value 1
ON
}
class Program {
// Main Method
static void Main(string[] args)
{
Console.WriteLine("Enter 0 or 1 to know the " +
"state of electric switch!");
byte i = Convert.ToByte(Console.ReadLine());
if (i == (byte)Button.OFF)
{
Console.WriteLine("The electric switch is Off");
}
else if (i == (byte)Button.ON)
{
Console.WriteLine("The electric switch is ON");
}
else
{
Console.WriteLine("byte cannot hold such" +
" large value");
}
}
}
}
input
1
output
Enter 0 or 1 to know the state of electric switch!
The electric switch is ON
แหล่งที่มา
Last updated