Most popular

วันอาทิตย์ที่ 24 กรกฎาคม พ.ศ. 2554

การสร้าง Generic Type ขึ้นใช้งานใน C#

Generic Type เป็นการทำงานแบบ Type safe ที่กำหนดไว้ตั้งแต่แรก ช่วยลดความผิดพลาดจากการทำ Unboxing ที่เกิดควาผิดพลาดได้บ่อยในตอนที่เรานำค่ามาใช้งาน แตกต่างกับการสร้าง Generic Type ที่จะกำหนด Type ข้อมูลตั้งแต่เริ่มแรกเพื่อให้รับข้อมูลตรงตาม Type ที่กำหนดไว้

หมายเหตุ
          ตัวอย่างการทำ Unboxing
          double a = 1.5;
          int b = (int)a;

ผู้เขียนจะแสดงตัวอย่างการใช้ Generic Type ที่สร้างขึ้น เพิ่มข้อมูลแบบ string และ int ใน ListBox

ในหน้า Design วาง ListBox เพียงตัวเดียว
สร้าง Generic Class ชื่อ myList เพื่อเก็บข้อมูล และแสดงข้อมูลทาง ListBox

    public class myList<T>
    {
        //สร้าง Collection List ที่เป็น Generic เพื่อเก็บข้อมูล
        private List<T> localList=new List<T>();

        //method Add รับค่า item ตาม Type ที่กำหนด
        public void Add(T item)
        {
            localList.Add(item);
        }

        //method สำหรับวนลูปแสดงค่าทาง ListBox
        public void printTo(ListBox listBox)
        {
            //เก็บค่า Type ที่ส่งเข้ามา
            Type itmType = typeof(T);
            foreach (T item in localList)
            {
                //ตรวจสอบว่าเป็น Type int หรือไม่
                if (itmType == typeof(int))
                {
                    //ถ้าเป็น Type int ให้นำค่ามาคูณ 2 
                    listBox.Items.Add(Convert.ToInt32(item) * 2);
                }
                else
                {
                    listBox.Items.Add(item);
                }
            }
        }
    }

ผู้เขียนได้เขียนคำสั่งการใช้งาน Generic ที่ Constructor ของฟอร์ม

    public partial class Form1 : Form
    {
        //ประกาศ Instance ของ myList 2 ตัว
        private myList<string> list1;
        private myList<int> list2;
        //ประกาศชื่อคนที่ต้องการทดสอบไว้ใน array
        private string[] friends = {"ศศิชา","วิชัย","ทิพภา","อภัสรา","พุทธชาด","ไชยา","กฤตธานนท์","จิรายุทธ์" };

        //Constructor ของฟอร์ม
        public Form1()
        {
            InitializeComponent();
            //สร้าง Generic Object ให้รับค่า string
            this.list1 = new myList<string>();
            //วนลูปชื่อคนใส่ใน Generic Object
            foreach (string item in friends)
                this.list1.Add(item);

            //ใช้ method แสดงข้อมูลทาง ListBox
            this.list1.printTo(this.listBox1);

            //สร้าง Generic Object ให้รับค่า int
            this.list2 = new myList<int>();
            //วนลูปชื่อคนใส่ใน Generic Object
            for (int i = 0; i < 20; i++)
                this.list2.Add(i);

            //ใช้ method แสดงข้อมูลทาง ListBox
            this.list2.printTo(this.listBox1);
        }
    }

ภาพรวมของ Generic Class และฟอร์ม ที่สร้างขึ้น


เมื่อรันโปรแกรม Generic ที่สร้างขึ้นจะทำงานได้ผลดังภาพ



ไม่มีความคิดเห็น:

แสดงความคิดเห็น