260 likes | 510 Views
C# เบื้องต้น ก่อนการเขียนเกมด้วย XNA. สุพจน์ สวัต ติวงศ์ tohpus@hotmail.com. โครงสร้างของ C#. Namespaces อาจจะมี structs , interfaces, delegates, และ enums Simplest case: single class, single file, default namespace. Unified Type System. Value กับ Reference. i. Simple Type.
E N D
C# เบื้องต้น ก่อนการเขียนเกมด้วย XNA สุพจน์ สวัตติวงศ์ tohpus@hotmail.com
โครงสร้างของ C# • Namespaces อาจจะมี structs, interfaces, delegates, และ enums • Simplest case: single class, single file, default namespace
การเปลี่ยนแปลงกันระหว่าง Simple Types
switch Statement • ตัวแปร condition ใน switch สามารถใช้ ได้ทั้ง numeric, char, enum และ String • ทุก case หากต้องการไม่ให้ทาต่อด้านล่างต้องมี break, return, throw, และ goto
Enumerations • การกำหนด Constant แบบ Enum • กำหนดโดยตรงใน namespace ดังนี้ • วิธีใช้งานดังต่อไปนี้ enum Color { red, blue, green } // values: 0, 1, 2 enum Access { personal = 1, group = 2, all = 4 } enum Access1 : byte { personal = 1, group = 2, all = 4 } Color c = Color.blue; // enumeration constants must be qualified Access a = Access.personal | Access.group; if ((Access.personal & a) != 0) Console.WriteLine("access granted");
การใช้เครื่องหมายของ enum ใน C# • Enumerations ไม่สามารถใช้ int แทนได้ (ยกเว้นถูกกำหนด Type ไว้ก่อน) • Enumeration types ถูก inherit จาก object จึงใช้ method (Equals, ToString, ...)ได้ • Class System.Enum ครอบคลุมการทำงานบน enumerations • (GetName, Format, GetValues, ...).
Arrays • การใช้ Array 1 มิติ
การใช้งานSystem.String • สามารถใช้ string ได้โดยตรงดังนี้ string s = "Suphot"; • สามารถใช้ + เพื่อบวก string ได้ เช่น s = s + " Sawattiwong"; • สามารถใช้ index ได้ เช่น s[i] • String มี length เช่น s.Length • Strings เป็นตัวแปร reference type แบบพิเศษ ซึ่งทำหน้าที่เป็น reference เฉพาะพฤติกรรมของมัน
การใช้งานSystem.String • สามารถใช้การเปรียบเทียบแบบ == และ!= ได้ เช่น if (s == "Alfonso") • Class String มี Methodอื่นเช่น CompareTo, IndexOf, StartsWith, Substring เป็นต้น
Structs • การกำหนด Struct • การใช้งาน structPoint { public int x, y;// fields public Point(int x, int y) { this.x = x; this.y = y; }// constructor public void MoveTo(int a, int b) { x = a; y = b; }// methods } Point p = new Point(3, 4);// constructor initializes object on the stack p.MoveTo(10, 20);// method call
Classes • การกำหนด Classes การใช้งาน class Rectangle { Point origin; public int width, height; public Rectangle() { origin = new Point(0,0); width = height = 0; } public Rectangle (Point p, int w, int h) { origin = p; width = w; height = h; } public void MoveTo (Point p) { origin = p; } } Rectangle r = new Rectangle(new Point(10, 20), 5, 5); int area = r.width * r.height; r.MoveTo(new Point(3, 3));
ความแตกต่างระหว่าง Classes และ Structs
Boxing /Unboxing • Boxing object obj = 3; โดย 3 จะเข้าไปอยู่ใน Heap ของ object • Unboxing int x = (int)obj; ค่าในตัวแปร objจะถูกเปลี่ยนเป็น int แล้วถูกเก็บมาในตัวแปร x