示例
Car.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IndexerExample
{
public class Car
{
private string[] _brands = new string[] { "BMW", "Skoda", "Honda" };
private string[] _names = new string[] { "first", "second", "third" };
public string this[int index]
{
set
{
this._brands[index] = value;
}
get
{
return this._brands[index];
}
}
public string this[string name]
{
set
{
this._names[Array.IndexOf(_names,name)] = value;
}
get
{
return this._names[Array.IndexOf(_names, name)];
}
}
}
}
Program.cs
namespace IndexerExample
{
internal class Program
{
static void Main(string[] args)
{
Car car = new Car();
Console.WriteLine(car[0]);
Console.WriteLine(car["first"]);
Console.WriteLine("Hello, World!");
}
}
}