我正在浏览一些代码并遇到索引器,我无法理解它是如何工作的,这是我的代码
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];
}
}
但是当我试图像这样做一个Indexer时,我收到了一个错误
相册[ “A”];
但与此同时,我使用这样的工作正常
。相册[ “A”]显示();
请帮助我了解Indexer的工作,谢谢
答案 0 :(得分:1)
您无法在C#中编写此类语句,它将发出以下错误:
错误CS0201:只能将赋值,调用,递增,递减和新对象表达式用作语句
此类声明不适合错误消息中告知的任何类别。
要修复错误,请将此语句分配给变量:
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;
}
}
}
}