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

วิธีสร้าง Property แบบ Read-Only ใน C#

ฟิลด์ที่ติดเครื่องหมาย readonly สามารถกำหนดค่าได้เพียงครั้งเดียวระหว่างการสร้างออบเจกต์ (ใน Constructor) และไม่สามารถเปลี่ยนแปลงได้ภายหลัง

ตัวอย่างการใช้ readonly field

class Employee
{
    readonly int salary;
    
    Employee(int salary)
    {
        this.salary = salary; // กำหนดค่าได้เฉพาะใน Constructor
    }
    
    void UpdateSalary()
    {
        // salary = 50000; // Compile-time Error: ไม่สามารถกำหนดค่าได้
    }
}

ตรวจสอบว่า Array เป็น Read-Only หรือไม่

ใช้ Property IsReadOnly ของ Array:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Lower
{
    class Program
    {
        static void Main(string[] args)
        {
            Array arr = Array.CreateInstance(typeof(String), 3);
            arr.SetValue("Maths", 0);
            arr.SetValue("Science", 1);
            arr.SetValue("PHP", 2);
            
            Console.WriteLine("isReadOnly: {0}", arr.IsReadOnly.ToString());
        }
    }
}

ผลลัพธ์

isReadOnly: False

Read-Only Property (Auto-implemented)

public class Person
{
    public string Name { get; } // Read-only property (C# 6+)
    
    public Person(string name)
    {
        Name = name; // กำหนดได้ใน Constructor
    }
}