Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

Collection Classes ใน C# คืออะไร

Collection Classes ใช้เพื่อวัตถุประสงค์ต่างๆ เช่น การจัดสรรหน่วยความจำแบบไดนามิกให้กับสมาชิก และการเข้าถึงรายการรายการผ่านดัชนี

คลาสใน Collections ประกอบด้วย:

ลำดับคลาส และ คำอธิบาย
1ArrayList
แสดงคอลเลกชันที่มีลำดับของออบเจ็กต์ที่เข้าถึงผ่านดัชนีได้แยกต่างหาก
2Hashtable
ใช้ Key ในการเข้าถึงสมาชิกในคอลเลกชัน
3SortedList
ใช้ Key และ Index ในการเข้าถึงรายการในลิสต์
4Stack
แสดงคอลเลกชันแบบ Last-in, First-out ของออบเจ็กต์
5Queue
แสดงคอลเลกชันแบบ First-in, First-out ของออบเจ็กต์
6BitArray
แสดงอาร์เรย์ของการแทนค่าบाइनอรีด้วย 1 และ 0

ตัวอย่างการใช้งาน BitArray ใน C#

using System; 
using System.Collections; 
namespace CollectionsApplication { 
    class Program { 
        static void Main(string[] args) { 
            // สร้างบิตอาร์เรย์ 2 ตัว ขนาด 8 
            BitArray ba1 = new BitArray(8); 
            BitArray ba2 = new BitArray(8); 
            byte[] a = { 60 }; 
            byte[] b = { 13 }; 
            // เก็บค่า 60 และ 13 ลงในบิตอาร์เรย์ 
            ba1 = new BitArray(a); 
            ba2 = new BitArray(b); 
            // เนื้อหาของ ba1 
            Console.WriteLine("Bit array ba1: 60"); 
            for (int i = 0; i < ba1.Count; i++) { 
                Console.Write("{0, -6} ", ba1[i]); 
            } 
            Console.WriteLine(); 
            // เนื้อหาของ ba2 
            Console.WriteLine("Bit array ba2: 13"); 
            for (int i = 0; i < ba2.Count; i++) { 
                Console.Write("{0, -6} ", ba2[i]); 
            } 
            Console.WriteLine(); 
            BitArray ba3 = new BitArray(8); 
            ba3 = ba1.And(ba2); 
            // เนื้อหาของ ba3 
            Console.WriteLine("Bit array ba3 after AND operation: 12"); 
            for (int i = 0; i < ba3.Count; i++) { 
                Console.Write("{0, -6} ", ba3[i]); 
            } 
            Console.WriteLine(); 
            ba3 = ba1.Or(ba2); 
            Console.WriteLine("Bit array ba3 after OR operation: 61"); 
            for (int i = 0; i < ba3.Count; i++) { 
                Console.Write("{0, -6} ", ba3[i]); 
            } 
            Console.WriteLine(); 
            Console.ReadKey(); 
        } 
    } 
}

ผลลัพธ์

Bit array ba1: 60 False False True True True True False False 
Bit array ba2: 13 True False True True False False False False 
Bit array ba3 after AND operation: 12 False False True True False False False False 
Bit array ba3 after OR operation: 61 True False True True False False False False