Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c#索引器

作者:——愿望   发布日期:2025-04-09   浏览:65

// 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] 是索引器的定义,它允许我们通过索引来访问和修改集合中的元素。
  • 索引器的 getset 方法分别用于获取和设置指定索引位置的元素。
  • Main 方法中,我们创建了一个 IndexedCollection<string> 对象,并通过索引器访问和修改其中的元素。

希望这个示例能帮助你理解 C# 中的索引器。

上一篇:c#读取csv文件

下一篇:c# mvc框架

大家都在看

c# 二进制

c# tcp client

c# type.gettype

c# sqlconnection

.net和c#

c#游戏开发

c#网络编程

c# rectangle

c# if else

c# rtsp

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站