Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

Constructor ในโปรแกรม C# คืออะไร

Constructor (ตัวสร้าง)

Constructor ของคลาสเป็นฟังก์ชันสมาชิกพิเศษที่ทำงานเมื่อสร้างออบเจ็กต์ใหม่ของคลาสนั้น

Constructor มีชื่อเหมือนชื่อคลาส และไม่มีประเภทการคืนค่า

class Demo {    public Demo() {} }

ตัวอย่างการใช้งาน Constructor

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

ผลลัพธ์

Object is being created Length of line : 6