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

C# 索引器:讓類別像陣列一樣存取元素的語法糖完整教學

     編輯:關於C語言

索引器概念

索引器讓類別/結構支援陣列語法存取內部資料:

myDepartment[0] = "Fred";
myDepartment[1] = "Barney";

語法定義

public 回傳型別 this[int index]
{
    get { ... }
    set { ... }
}

完整範例:Department 類別

using System;

public class Department
{
    private string name;
    private const int MAX_EMPLOYEES = 10;
    private string[] employees = new string[MAX_EMPLOYEES];

    public Department(string deptName) => name = deptName;

    public string this[int index]
    {
        get
        {
            if (index >= 0 && index < MAX_EMPLOYEES)
                return employees[index];
            throw new IndexOutOfRangeException();
        }
        set
        {
            if (index >= 0 && index < MAX_EMPLOYEES)
                employees[index] = value;
            else
                throw new IndexOutOfRangeException();
        }
    }
}

使用方式

using System;

public class SalesDept
{
    public static void Main(string[] args)
    {
        Department sales = new Department("Sales");
        sales[0] = "Nikki";
        sales[1] = "Becky";
        Console.WriteLine("The sales team is {0} and {1}", sales[0], sales[1]);
    }
}

索引器讓自訂集合類別擁有直覺的陣列存取體驗。

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