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

ขอบเขตของตัวแปรสมาชิก Public ใน C#

คีย์เวิร์ด public ใน C# กำหนดให้สมาชิก (Field, Property, Method) เข้าถึงได้จาก ที่ใดก็ได้ ทั้งในและนอก Assembly ไม่มีข้อจำกัด

ขอบเขต (Scope) ของ public member

  • ภายในคลาสเดียวกัน: เข้าถึงได้
  • คลาสลูก (Derived Class): เข้าถึงได้
  • คลาสอื่นใน Assembly เดียวกัน: เข้าถึงได้
  • คลาสใน Assembly อื่น (Reference มา): เข้าถึงได้

สรุป: เข้าถึงได้จากทุกที่ ที่มี Reference ไปยัง Assembly นั้น

ตัวอย่างการเข้าถึง Public Field

using System;

namespace RectangleApplication
{
    class Rectangle
    {
        // Public fields - เข้าถึงได้จากภายนอก
        public double length;
        public double width;
        
        public double GetArea() => length * width;
        
        public void Display()
        {
            Console.WriteLine($"ความยาว: {length}");
            Console.WriteLine($"ความกว้าง: {width}");
            Console.WriteLine($"พื้นที่: {GetArea()}");
        }
    }
    
    class ExecuteRectangle
    {
        static void Main(string[] args)
        {
            Rectangle r = new Rectangle();
            
            // เข้าถึง public fields จากภายนอกคลาสโดยตรง
            r.length = 4.5;
            r.width = 3.5;
            
            r.Display();
            Console.ReadLine();
        }
    }
}

ผลลัพธ์

ความยาว: 4.5
ความกว้าง: 3.5
พื้นที่: 15.75

แนวทางปฏิบัติที่ดี (Best Practice)

แม้ public field จะทำงานได้ แต่ควรใช้ Property แทน:

// แทน public field
public double Length { get; set; }

// หรือมี Logic เพิ่ม
private double _length;
public double Length
{
    get => _length;
    set => _length = value > 0 ? value : throw new ArgumentException("Length must be positive");
}

เหตุผลใช้ Property แทน Public Field

  • ควบคุม Validation ได้
  • เปลี่ยน Implementation ภายในโดยไม่กระทบ Caller
  • รองรับ Data Binding, Serialization, Reflection ได้ดีกว่า
  • สอดคล้องกับ Encapsulation Principle