Dùng toán tử new để instantiate class:
Line line = new Line();
Gọi method qua instance:
line.SetLength(6.0);
Ví dụ
using System;
namespace LineApplication
{
class Line
{
private double length;
public Line()
{
Console.WriteLine("Object được tạo");
}
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("Chiều dài: {0}", line.GetLength());
}
}
}
Kết quả
Object được tạo Chiều dài: 6
Chi tiết:
newcấp phát memory trên heap, gọi constructor- Struct:
newoptional (default parameterless constructor) - Object initializer:
var line = new Line { Length = 6 };(cần property public) - Factory method:
Line.Create(6)pattern - DI Container:
serviceProvider.GetService<Line>()