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

Biến Static và biến Instance (Class Variables) trong C#

Biến Static

Thuộc về class, không phải instance. Chia sẻ bởi tất cả instance. Dùng cho hằng số, counter, shared state.

using System;

namespace StaticVarApplication
{
    class StaticVar
    {
        public static int num;
        public void Count() { num++; }
        public int GetNum() { return num; }
    }
    
    class StaticTester
    {
        static void Main(string[] args)
        {
            StaticVar s1 = new StaticVar();
            StaticVar s2 = new StaticVar();
            
            s1.Count(); s1.Count(); s1.Count();
            s2.Count(); s2.Count(); s2.Count();
            
            Console.WriteLine("s1.num: {0}", s1.GetNum()); // 6
            Console.WriteLine("s2.num: {0}", s2.GetNum()); // 6
            Console.ReadKey();
        }
    }
}

Kết quả

s1.num: 6
s2.num: 6

Biến Instance (Class Variables / Fields)

Thuộc về từng object, private để encapsulation, truy cập qua property/method.

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();
            box1.SetLength(6); box1.SetBreadth(7); box1.SetHeight(5);
            Console.WriteLine("Thể tích Box1: {0}", box1.GetVolume()); // 210
            
            Box box2 = new Box();
            box2.SetLength(12); box2.SetBreadth(13); box2.SetHeight(10);
            Console.WriteLine("Thể tích Box2: {0}", box2.GetVolume()); // 1560
            Console.ReadKey();
        }
    }
}

So sánh

Đặc điểmStaticInstance
Lưu trữMột bản cho cả classMỗi object một bản
Truy cậpClassName.StaticFieldobj.InstanceField
Khởi tạoStatic constructor / inlineInstance constructor
Thread safetyCần lock nếu ghiTách biệt per instance