无法理解 C# 中的索引器

Not able to understand Indexer in C#

我正在浏览一些代码并遇到索引器,但我无法理解它是如何工作的,这是我的代码

public class FlyweightFactory
    {
        Dictionary<string, FlyweightFactory> flyweights = new Dictionary<string, FlyweightFactory>();
        public void display() { }
        public FlyweightFactory this[string index]
        {
            get
            {
                if (!flyweights.ContainsKey(index))
                    flyweights[index] = new FlyweightFactory();
                return flyweights[index];
            }
        }
    }
    class Client
    {
        // Shared state - the images
        static FlyweightFactory album = new FlyweightFactory();
        static void Main()
        {
            Client client = new Client();
            album["A"].display();
            Console.ReadLine();
        }

    }

在这段代码中,我创建了一个这样的索引器

public FlyweightFactory this[string index]
        {
            get
            {
                if (!flyweights.ContainsKey(index))
                    flyweights[index] = new FlyweightFactory();
                return flyweights[index];
            }
        }

但是当我尝试制作这样的索引器时出现错误

album["A"];

但同时当我这样使用时它工作正常

album["A"].display();

请帮助我了解 Indexer 的工作原理,谢谢

您不能在 C# 中编写这样的语句,它会发出以下错误:

error CS0201: 只有assignment, call, increment, decrement, new 对象表达式可以作为语句使用

此类陈述不符合错误消息中所述的任何类别。

要修复错误,请将此语句分配给变量:

var myValue = album["A"];

现在索引器:

它允许您通过特定键类型访问集合中的项目,在数组中您通常通过索引访问项目,例如:

int[] ints = {0, 1, 2, 3};
var int1 = ints[0]; // get first element

但是你可以实现不同于 int 的类型,这里我使用了 string:

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;

namespace Tests
{
    public partial class MainWindow
    {
        public MainWindow()
        {
            InitializeComponent();

            // generate some data
            var artist = new Artist {Name = "Britney", Surname = "Spears"};
            var artists = new[] {artist};
            var collection = new ArtistCollection(artists);

            // find an artist by its name, using the custom indexer
            var artist1 = collection["Britney"];
        }
    }

    public class Artist
    {
        public string Name { get; set; }
        public string Surname { get; set; }
    }

    public class ArtistCollection : Collection<Artist>
    {
        public ArtistCollection()
        {
        }

        public ArtistCollection(IList<Artist> list) : base(list)
        {
        }

        /// <summary>
        ///     Gets an artist by name.
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public Artist this[string name]
        {
            get
            {
                if (name == null)
                    throw new ArgumentNullException(nameof(name));
                var artist = this.SingleOrDefault(s => s.Name == name);
                return artist;
            }
        }
    }
}