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

Các hàm thành viên (member functions) của lớp trong C#

Member function (phương thức) là hàm có định nghĩa hoặc nguyên mẫu bên trong định nghĩa class. Nó thao tác trên đối tượng của class đó và truy cập được tất cả các thành viên của đối tượng.

Ví dụ member functions:

public void SetLength(double len) { length = len; }
public void SetBreadth(double bre) { breadth = bre; }
public double GetVolume() { return length * breadth * height; }

Ví dụ hoàn chỉnh: Lớp Box với member functions

using System;

namespace BoxApplication
{
    class Box
    {
        private double length;
        private double breadth;
        private double height;
        
        public void SetLength(double len) { length = len; }
        public void SetBreadth(double bre) { breadth = bre; }
        public void SetHeight(double hei) { height = hei; }
        public double GetVolume() { return length * breadth * height; }
    }
    
    class Boxtester
    {
        static void Main(string[] args)
        {
            Box Box1 = new Box();
            Box Box2 = new Box();
            double volume;
            
            // Box 1
            Box1.SetLength(8.0);
            Box1.SetBreadth(9.0);
            Box1.SetHeight(7.0);
            
            // Box 2
            Box2.SetLength(18.0);
            Box2.SetBreadth(20.0);
            Box2.SetHeight(17.0);
            
            volume = Box1.GetVolume();
            Console.WriteLine("Volume of Box1 : {0}", volume);
            
            volume = Box2.GetVolume();
            Console.WriteLine("Volume of Box2 : {0}", volume);
            Console.ReadKey();
        }
    }
}

Kết quả

Volume of Box1 : 504
Volume of Box2 : 6120

Phân loại: Instance method (cần object), Static method (gọi qua class), Constructor (khởi tạo), Property (get/set), Indexer, Operator overloading.