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

คลาส (Class) ใน C#

คลาสใน C# เป็น "แม่แบบ" (Blueprint) สำหรับการสร้างชนิดข้อมูล (Data Type) โดยออบเจ็กต์ (Object) คืออินสแตนซ์ (Instance) ของคลาส ส่วนเมธอดและตัวแปรที่ประกอบเป็นคลาสเรียกว่า "สมาชิกของคลาส" (Members of the class)

รูปแบบทั่วไปของคลาส

<access specifier> class class_name {
    // member variables
    <access specifier><data type> variable1;
    <access specifier><data type> variable2;
    ...
    <access specifier><data type> variableN;
    // member methods
    <access specifier><return type> method1(parameter_list) {
        // method body
    }
    <access specifier><return type> method2(parameter_list) {
        // method body
    }
    ...
    <access specifier><return type> methodN(parameter_list) {
        // method body
    }
}

ตัวอย่างการสร้างคลาส

using System;
namespace Demo {
    class Box {
        public double length;   // ความยาวของกล่อง
        public double breadth;  // ความกว้างของกล่อง
        public double height;   // ความสูงของกล่อง
    }
    class Boxtester {
        static void Main(string[] args) {
            Box Box1 = new Box(); // ประกาศ Box1 เป็นชนิด Box
            Box Box2 = new Box(); // ประกาศ Box2 เป็นชนิด Box
            double volume = 0.0;  // เก็บปริมาตรของกล่อง
            // ข้อมูลกล่อง 1
            Box1.height = 5.0;
            Box1.length = 6.0;
            Box1.breadth = 7.0;
            // ข้อมูลกล่อง 2
            Box2.height = 10.0;
            Box2.length = 12.0;
            Box2.breadth = 13.0;
            // ปริมาตรกล่อง 1
            volume = Box1.height * Box1.length * Box1.breadth;
            Console.WriteLine("Volume of Box1 : {0}", volume);
            // ปริมาตรกล่อง 2
            volume = Box2.height * Box2.length * Box2.breadth;
            Console.WriteLine("Volume of Box2 : {0}", volume);
            Console.ReadKey();
        }
    }
}

ผลลัพธ์

Volume of Box1 : 210
Volume of Box2 : 1560