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

Static vs Non-Static Method trong C#

Khai báo hàm thành viên static. Chỉ truy cập biến static. Hàm static tồn tại trước khi object tạo.

Static class không khởi tạo được, chỉ chứa static member.

Static method dùng từ khóa static:

public static int getNum() {
    return num;
}

Ví dụ

using System;

namespace StaticVarApplication {
    class StaticVar {
        public static int num;
        public void count() {
            num++;
        }
        public static int getNum() {
            return num;
        }
    }
    class StaticTester {
        static void Main(string[] args) {
            StaticVar s = new StaticVar();
            s.count();
            s.count();
            s.count();
            s.count();
            s.count();
            s.count();
            Console.WriteLine("Biến num: {0}", StaticVar.getNum());
            Console.ReadKey();
        }
    }
}