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

Default Constructor (Constructor mặc định) trong C#

Class constructor là member function đặc biệt thực thi khi tạo object mới. Default constructor KHÔNG có tham số.

Ví dụ làm việc với default constructor:

Ví dụ

using System; 
namespace LineApplication { 
    class Line { 
        private double length; 
        public Line(double len) { // Parameterized constructor 
            Console.WriteLine("Object is being created, length = {0}", len); 
            length = len; 
        } 
        public void setLength(double len) { length = len; } 
        public double getLength() { return length; } 
        static void Main(string[] args) { 
            Line line = new Line(10.0); 
            Console.WriteLine("Length of line : {0}", line.getLength()); 
            // set line length 
            line.setLength(6.0); 
            Console.WriteLine("Length of line : {0}", line.getLength()); 
            Console.ReadKey(); 
        } 
    } 
}

Kết quả

Object is being created, length = 10
Length of line : 10
Length of line : 6

Lưu ý: ví dụ này dùng parameterized constructor Line(double len), không phải default constructor. Default constructor là Line() không tham số.