คลาส คือแม่แบบ (template) ของโปรแกรมเพื่อนำมาสร้างออบเจ็คในโปรแกรม
รูปแบบการสร้าง Calss
class identifier { // class members and specifications }
ตัวอย่างการสร้าง Class ของนักเรียน
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Class { class Program { static void Main(string[] args) { Student st = new Student(); st.CheckScore(); Console.ReadLine(); } } class Student { public static int score = 3; private float totalscore = 10; public int WordJobPlusScore = 3; public void CheckScore() { if (totalscore == score) { Console.WriteLine("Goods Top Score : "+ score); } else { AddWord(); } } public void AddWord() { score += WordJobPlusScore; ShowScore(); } public void ShowScore() { Console.WriteLine("Score + WordJob : " + score); } } }
ตัวอย่างเป็นการสร้าง Class แสดงคะแนนนักเรียน คนมีคะแนนไม่ถึง 10 ให้ทำงานเพิ่ม เพื่อบวกคะแนน
เมื่อมีการอินสแตนคลาสนี้ คลาสนี้จะกำหนดค่าเริ่มต้น score,studentName ตามพารามิเตอร์ที่ส่งมาทันที
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Class { class student { int score = 0; string studentName = ""; public student(string studentName,int score) { this.score = score; this.studentName = studentName; } } }