Sử dụng toán tử mới để khởi tạo một lớp trong C #.
Giả sử lớp của chúng ta là Line. Instantiation sẽ tạo một đối tượng mới như hình dưới đây -
Line line = new Line();
Sử dụng đối tượng, bây giờ bạn có thể gọi phương thức -
line.setLength(6.0);
Hãy để chúng tôi xem ví dụ -
Ví dụ
using System;
namespace LineApplication {
class Line {
private double length; // Length of a line
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();
// set line length
line.setLength(6.0);
Console.WriteLine("Length of line : {0}", line.getLength());
}
}
} Đầu ra
Object is being created Length of line : 6