วันจันทร์ที่ 15 ธันวาคม พ.ศ. 2551

การสร้างและใช้งาน Collection.Generic

Generic เป็นเครื่องมือที่ช่วยให้ผู้พัฒนา Collection Class สามารถนำ Class ที่สร้างไว้นำกลับมาใช้งานได้ง่ายขึ้นโดยไม่จำเป็นต้องคำนึงถึงชนิดของตัวแปรที่บรรจุอยู่ใน Collection Class เหล่านั้นในตอนออกแบบ แต่จะทำการกำหนดชนิดของตัวแปรให้กับ Class เมื่อจะนำ Class เหล่านั้นไปใช้งาน

ตัวอย่าง
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace ConsoleApplication9
{
     // กำหนดตัวแปรเป็นชนิด T ภายใต้เครื่องหมาย "< >"
    public class myCollection<T>
    {
         // นำชนิดตัวแปรนั้นมาใช้งานเช่นเดียวกับชนิดตัวแปรอื่นๆ
        T[] myStack = new T[50];

        public T this[int idx]
        {
            get
            {
                return myStack[idx];
            }
            set
            {
                myStack[idx] = value;
            }
        }

    }

    public class Student
    {
        private String _std;

        public Student(String name)
        {
            _std = name;
        }
        public override string ToString()
        {
            return _std;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            // เมื่อนำมาใช้งาน ให้กำหนดชนิดของตัวแปรตามที่ต้องการ ในที่นี้ให้แทนด้วย Class Student ที่ได้กำหนดไว้ (อาจกำหนดเป็น String, Int, ... ก็ได้แล้วแต่จะใช้)
            myCollection<Student>             mCollec = new             myCollection<Student>();

            //หลังจากที่กำหนดเรียบร้อยแล้ว จะสามารถนำตัวแปรนั้นมาใช้งานได้ทันที โดยชนิดของตัวแปรนั้นจะเป็นไปตามที่กำหนดไว้ในขั้นตอนการประการตัวแปร
            mCollec[0] = new Student("Jor");
            mCollec[1] = new Student("Ann");
            mCollec[2] = new Student("Aae");

            for(int item = 0; item < 3; item++)
                Console.WriteLine(mCollec[item]);
            Console.ReadKey();
        }
    }
}