首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

Effective C# 原則 7:選擇不可變的原子實值型別(三)

     編輯:關於C語言

建立不可變 Address 結構

public readonly struct Address
{
    public readonly string Line1;
    public readonly string Line2;
    public readonly string City;
    public readonly string State;
    public readonly int ZipCode;

    public Address(string line1, string line2, string city, string state, int zipCode)
    {
        Line1 = line1;
        Line2 = line2;
        City = city;
        State = state;
        ZipCode = zipCode;
        ValidateState(state);
        ValidateZip(zipCode);
    }

    private static void ValidateState(string state) { /* ... */ }
    private static void ValidateZip(int zip) { /* ... */ }
}

使用方式:以新實例取代修改

// 建立
Address a1 = new Address("111 S. Main", "", "Anytown", "IL", 61111);

// 修改城市 → 建立新實例
a1 = new Address(a1.Line1, a1.Line2, "Ann Arbor", "MI", 48103);

關鍵觀念

  • 預設建構函式仍可用(產生全 null/0 的實例),無法禁止
  • 複製建構函式非必要,結構賦值本身即為淺層複製(高效)
  • 所有欄位 readonly,建構函式後不可修改
  • 移除所有 set 存取器,僅保留 get

為什麼這樣更好?

避免了「修改一個欄位導致物件暫態無效」的問題。物件一生要么是有效初始值,要么是經驗證的新值,不存在中間狀態。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved