首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C# 索引器深度解析:Library 類中 lib[i] = b 的含義與實現機制

     編輯:程式設計綜合問答

代碼片段

class Library {
    Book[] book;
    public Library(int len) { book = new Book[len]; }
    // 索引器定義
    public Book this[int idx] {
        get { return book[idx]; }
        set { book[idx] = value; }
    }
}

// 主程序中
Library lib = new Library(length);
for (int i = 0; i < length; i++) {
    Book b = new Book();
    b.Bid = Console.ReadLine();
    b.Bname = Console.ReadLine();
    lib[i] = b;  // 核心語句
}

核心解答

lib[i] = b; **調用 Library 類索引器的 set 存取器**,將 Book 對象 b 存入內部 Book[] book 數組的第 i 個位置。

索引器語法糖本質

完整類設計解析

public class Book {
    public string Bid { get; set; }   // 自動屬性(C# 3.0+)
    public string Bname { get; set; }
}

public class Library {
    private Book[] books;  // 私有字段,封裝內部存儲
    
    public Library(int capacity) {
        if (capacity < 0) throw new ArgumentException("容量不能為負");
        books = new Book[capacity];
    }
    
    // 索引器:提供類陣列訪問體驗
    public Book this[int index] {
        get {
            if (index < 0 || index >= books.Length)
                throw new IndexOutOfRangeException($"索引 {index} 超出範圍 [0, {books.Length-1}]");
            return books[index];
        }
        set {
            if (index < 0 || index >= books.Length)
                throw new IndexOutOfRangeException($"索引 {index} 超出範圍 [0, {books.Length-1}]");
            books[index] = value ?? throw new ArgumentNullException(nameof(value));
        }
    }
    
    // 額外實用成員
    public int Count => books.Length;
    public IEnumerable Books => books.Where(b => b != null);
}

索引器進階用法

多參數索引器(如矩陣)

public class Matrix {
    private double[,] data;
    public double this[int row, int col] {
        get => data[row, col];
        set => data[row, col] = value;
    }
}
// 使用:matrix[2, 3] = 3.14;

字符串索引器(如字典包裝)

public class Config {
    private Dictionary dict = new();
    public string this[string key] {
        get => dict.TryGetValue(key, out var v) ? v : null;
        set => dict[key] = value;
    }
}
// 使用:config["db.connection"] = "server=...";

總結

lib[i] = b 是 C# **索引器**語法糖,編譯為 set_Item(i, b) 調用。它讓自定義類擁有原生陣列般的訪問體驗,內部封裝 Book[] 數組,實現了「圖書館」對「圖書」集合的面向對象建模。掌握索引器,能寫出更符合領域語言、更優雅的 C# 代碼。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
語法編譯後等價調用說明
lib[i] = b;lib.set_Item(i, b);set 存取器
Book b = lib[i];Book b = lib.get_Item(i);get 存取器