C#的索引器

索引器

在 C# 中,索引器(Indexer)是一种特殊的属性,允许通过类的实例像访问数组一样访问对象的元素。索引器允许将类的实例作为集合来使用,可以按照自定义的方式访问类中的元素。

索引器的定义类似于属性,但在属性名称后加上索引参数。它使用this关键字来定义和访问实例的索引器。索引器可以有一个或多个参数,用于指定要访问的元素。

下面是一个简单的示例,演示了如何创建和使用索引器:

class MyCollection
{
    private string[] items = new string[5];

    public string this[int index]
    {
        get { return items[index]; }
        set { items[index] = value; }
    }
}

class Program
{
    static void Main(string[] args)
    {
        MyCollection collection = new MyCollection();
        collection[0] = "Apple";
        collection[1] = "Banana";
        collection[2] = "Orange";

        Console.WriteLine(collection[0]); // 输出 "Apple"
        Console.WriteLine(collection[1]); // 输出 "Banana"
        Console.WriteLine(collection[2]); // 输出 "Orange"
    }
}

在上面的例子中,MyCollection 类定义了一个索引器 this[int index],允许按照整数索引访问 items 数组中的元素。在 Main 方法中,我们实例化了一个 MyCollection 对象,并通过索引器设置和获取元素的值。

需要注意的是,索引器的参数可以是一个或多个,可以是任意类型,不仅限于整数。

简单的字符串队列:

class StringQueue
{
    private List<string> items = new List<string>();

    public string this[int index]
    {
        get { return items[index]; }
        set { items[index] = value; }
    }

    public void Enqueue(string item)
    {
        items.Add(item);
    }

    public string Dequeue()
    {
        string item = items[0];
        items.RemoveAt(0);
        return item;
    }
}

class Program
{
    static void Main(string[] args)
    {
        StringQueue queue = new StringQueue();
        queue.Enqueue("Apple");
        queue.Enqueue("Banana");

        Console.WriteLine(queue[0]); // 输出 "Apple"
        Console.WriteLine(queue[1]); // 输出 "Banana"
        
        string item = queue.Dequeue();
        Console.WriteLine(item); // 输出 "Apple"
    }
}

在这个例子中,我定义了一个简单的字符串队列 StringQueue,其中的索引器为 this[int index],它可以按索引访问队列中的元素,还提供了入队和出队的方法来操作队列。

  1. 二维矩阵:

    class Matrix
    {
        private int[,] matrix = new int[3, 3];
    
        public int this[int row, int column]
        {
            get { return matrix[row, column]; }
            set { matrix[row, column] = value; }
        }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            Matrix matrix = new Matrix();
            matrix[0, 0] = 1;
            matrix[1, 1] = 2;
            matrix[2, 2] = 3;
    
            Console.WriteLine(matrix[0, 0]); // 输出 1
            Console.WriteLine(matrix[1, 1]); // 输出 2
            Console.WriteLine(matrix[2, 2]); // 输出 3
        }
    }
    

    在这个例子中,我创建了一个表示二维矩阵的类 Matrix,其中的索引器 this[int row, int column] 可以通过行和列的索引访问矩阵中的元素,使用二维数组来存储数据。

这些例子展示了如何使用索引器来访问自定义类中的元素,这样可以使代码更易读、语义更明确,同时提供了更方便的操作方式。索引器的灵活性使得它在构建集合类和数据结构时非常有用。


总结起来,索引器在 C# 中提供了一种方便的方式来访问类实例的元素,使其像访问数组一样简单和直观。

你可能感兴趣的:(学习C#的笔记,c#,开发语言)