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

Đối tượng (Objects) trong C#

Như ngôn ngữ OOP khác, C# có object và class. Object là thực thể thực tế, instance của class. Truy cập thành viên class qua object.

Dùng toán tử chấm (.) sau tên object: Box b1 = new Box(); -> b1.height = 7.0; hoặc b1.getVolume();

Ví dụ

using System;

namespace BoxApplication {
    class Box {
        private double length, breadth, 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); // 210
            volume = Box2.getVolume();
            Console.WriteLine("Volume of Box2: {0}", volume); // 1560
            Console.ReadKey();
        }
    }
}

Kết quả

Volume of Box1: 210
Volume of Box2: 1560