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

วิธีสร้าง Instance ของ Class ใน C#

ใช้ตัวดำเนินการ new เพื่อสร้าง Instance ของ Class

สมมติคลาสชื่อ Line:

Line line = new Line();

เรียกใช้เมธอดผ่านอ็อบเจ็กต์:

line.setLength(6.0);

ตัวอย่าง

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());
        }
    }
}

ผลลัพธ์

Object is being created
Length of line : 6