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

Khác biệt giữa Class và Object trong C#

Khi định nghĩa class, bạn định nghĩa blueprint cho kiểu dữ liệu.

Objects là instances (thể hiện) của class. Methods và variables cấu thành class gọi là members của class.

Để truy cập class members, dùng toán tử chấm (.) sau tên object. Toán tử chấm liên kết tên object với tên member, ví dụ:

Box Box1 = new Box();

Box1 là object. Dùng để truy cập members:

Box1.height = 7.0;

Cũng dùng để gọi member functions:

Box1.getVolume();

Ví dụ minh họa object và class trong C#:

Ví dụ

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; 
            Box1.setLength(6.0); 
            Box1.setBreadth(7.0); 
            Box1.setHeight(5.0); 
            Box2.setLength(12.0); 
            Box2.setBreadth(13.0); 
            Box2.setHeight(10.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 : 210
Volume of Box2 : 1560