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

Khởi tạo instance class trong C#

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:

  • new cấp phát memory trên heap, gọi constructor
  • Struct: new optional (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>()