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

Instance (Thể hiện) của Class trong C#

Class instances là objects. Giống ngôn ngữ OOP khác, C# có object và classes. Objects là thực thể thực tế và instance của class. Truy cập members của class dùng object.

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:

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