Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Các biến thành viên (member variables) của lớp trong C#

Một class là bản thiết kế (blueprint) chứa các biến thành viên (fields) và hàm thành viên (methods), mô tả hành vi của đối tượng.

Cú pháp khai báo class:

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

Member variables (fields) là các thuộc tính của đối tượng. Thường để private để encapsulation (đóng gói), truy cập qua property hoặc public method.

Ví dụ: Lớp Rectangle với member variables length, width

using System;

namespace RectangleApplication
{
    class Rectangle
    {
        // Member variables (private - encapsulation)
        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();
        }
    }
}

Kết quả

Length: 10
Width: 14
Area: 140

Lưu ý: Mỗi instance của Rectangle có bản sao riêng của length và width. Dùng property (get/set) thay vì field public là best practice hiện đại.