// C# 索引器示例代码
using System;
using System.Collections.Generic;
public class IndexedCollection<T>
{
    private List<T> items = new List<T>();
    // 定义一个索引器,允许通过索引访问集合中的元素
    public T this[int index]
    {
        get
        {
            if (index < 0 || index >= items.Count)
                throw new IndexOutOfRangeException("索引超出范围");
            return items[index];
        }
        set
        {
            if (index < 0 || index >= items.Count)
                throw new IndexOutOfRangeException("索引超出范围");
            items[index] = value;
        }
    }
    // 添加元素的方法
    public void Add(T item)
    {
        items.Add(item);
    }
}
public class Program
{
    public static void Main()
    {
        IndexedCollection<string> collection = new IndexedCollection<string>();
        collection.Add("Apple");
        collection.Add("Banana");
        collection.Add("Cherry");
        // 使用索引器访问元素
        Console.WriteLine(collection[0]);  // 输出: Apple
        Console.WriteLine(collection[1]);  // 输出: Banana
        Console.WriteLine(collection[2]);  // 输出: Cherry
        // 修改元素
        collection[1] = "Blueberry";
        Console.WriteLine(collection[1]);  // 输出: Blueberry
    }
}IndexedCollection<T> 类中定义了一个泛型列表 items,用于存储集合中的元素。this[int index] 是索引器的定义,它允许我们通过索引来访问和修改集合中的元素。get 和 set 方法分别用于获取和设置指定索引位置的元素。Main 方法中,我们创建了一个 IndexedCollection<string> 对象,并通过索引器访问和修改其中的元素。希望这个示例能帮助你理解 C# 中的索引器。
上一篇:c#字符串转byte数组
下一篇:c# mvc框架
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站