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

Parameterized Constructor ใน C#

Parameterized Constructor (Constructor ที่มีพารามิเตอร์) ใน C#

Constructor ที่รับพารามิเตอร์ ใช้สำหรับ Initialize Object ด้วยค่าเริ่มต้น ทันทีตอนสร้าง

ไวยากรณ์


public ClassName(ParameterType paramName)
{
    // Initialize fields with parameters
}

ตัวอย่าง: Класс Line


using System;

namespace Demo
{
    class Line
    {
        private double length;
        
        // Parameterized Constructor
        public Line(double len)
        {
            Console.WriteLine($"Object is being created, length = {len}");
            length = len;
        }
        
        public void SetLength(double len) => length = len;
        public double GetLength() => length;
        
        static void Main(string[] args)
        {
            Line line = new Line(10.0); // สร้างพร้อมส่งค่า 10.0
            Console.WriteLine($"Length of line: {line.GetLength()}"); // 10
            
            line.SetLength(6.0);
            Console.WriteLine($"Length of line: {line.GetLength()}"); // 6
            
            Console.ReadKey();
        }
    }
}

ผลลัพธ์


Object is being created, length = 10
Length of line: 10
Length of line: 6

Constructor Overloading (หลาย Constructor)


class Point
{
    public int X, Y;
    
    // Default Constructor
    public Point() : this(0, 0) {}
    
    // Parameterized Constructor
    public Point(int x, int y)
    {
        X = x; Y = y;
    }
    
    // Constructor อีกแบบ
    public Point(Point other) : this(other.X, other.Y) {}
}

// ใช้งาน
var p1 = new Point();        // (0,0)
var p2 = new Point(3, 4);    // (3,4)
var p3 = new Point(p2);      // (3,4) Copy

Best Practices

  • ใช้ this() เรียก Constructor อื่นเพื่อลดโค้ดซ้ำ
  • Validate พารามิเตอร์ใน Constructor (Throw ArgumentException)
  • Initialize Readonly Fields ใน Constructor เท่านั้น
  • หลีกเลี่ยง Logic ซับซ้อน/IO ใน Constructor (Factory Method แทน)
  • Dependency Injection: รับ Interface ผ่าน Constructor

Record Types (C# 9+) - Alternative


// Record มี Constructor, Equality, With-Expression Built-in
public record Person(string Name, int Age);
var p = new Person("Tom", 25);