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

ตัวแปรสมาชิก (Member Variables) ของคลาสใน C# คืออะไร

คลาสเป็นแม่แบบ (blueprint) ที่มีตัวแปรสมาชิกและฟังก์ชันใน C# อธิบายพฤติกรรมของออบเจ็กต์

ไวยากรณ์ของคลาส:

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

ตัวแปรสมาชิกคือแอตทริบิวต์ของออบเจ็กต์ (มุมมองการออกแบบ) และมักถูกเก็บเป็น private เพื่อทำ encapsulation สามารถเข้าถึงได้เฉพาะผ่าน public member functions

ตัวอย่าง

using System;

namespace RectangleApplication {
    class Rectangle {
        // member variables
        private double length;
        private double width;
        
        public void Acceptdetails() {
            length = 10;
            width = 14;
        }
        
        public double GetArea() {
            return length * width;
        }
        
        public void Display() {
            Console.WriteLine("Length: {0}", length);
            Console.WriteLine("Width: {0}", width);
            Console.WriteLine("Area: {0}", GetArea());
        }
    }
    
    class ExecuteRectangle {
        static void Main(string[] args) {
            Rectangle r = new Rectangle();
            r.Acceptdetails();
            r.Display();
            Console.ReadLine();
        }
    }
}

ผลลัพธ์

Length: 10
Width: 14
Area: 140