C#索引器语法:
[访问修饰符] 数据类型 this [数据类型标识符]。
示例1:
using System;
using System.Collections.Generic;
using System.Text;
namespace PH6_2
{
class Photo
{
string _title;
public Photo(string title)
{
_title = title;
}
public string Title
{
get
{
return _title;
}
set
{
_title = value;
}
}
}
class Album
{
Photo[] photos;
public Album(int capacity)
{
photos = new Photo[capacity];
}
public Photo this[int index]
{
get
{
if (index < 0 || index >= photos.Length)
{
Console.WriteLine("索引无效");
return null;
}
return photos[index];
}
set
{
if (index < 0 || index >= photos.Length)
{
Console.WriteLine("索引无效");
return;
}
photos[index] = value;
}
}
public Photo this[string title]
{
get
{
foreach(Photo photo in photos)
{
if (photo.Title==title)
{
return photo;
}
}
return null;
}
}
}
class TestIndex
{
static void Main(string[] args)
{
Photo first = new Photo("first");
Photo second = new Photo("second");
Photo third = new Photo("third");
Album album = new Album(3);
album[0] = first;
album[1] = second;
album[2] = third;
Console.WriteLine("第2张照片:" + album[1].Title);
Console.WriteLine(album["third"].Title);
}
}
}
运行效果如下:
注意,不能定义两个相同数据类型的索引器,但是可以定义不同数据类型的索引器,其返回值可以相同。
例如下面的示例是不正确的:两个索引器,索引都是int,编译报错: 类型“PH6_2.TestIndex”已定义了一个名为“this”的具有相同参数类型的成员 。
class TestIndex
{
int[] num1s ={ 1, 2, 3, 4, 5 };
string[] s ={ "a", "b", "c" };
public int this[int index]
{
get
{
return num1s[index];
}
}
public string this[int index]
{
get
{
return s[index];
}
}
static void Main(string[] args)
{
TestIndex testIndex = new TestIndex();
uint i = 2;
Console.WriteLine(testIndex[i]);
}
}
可以将第2个索引器的索引改为uint,则编译通过。如下:
class TestIndex
{
int[] num1s ={ 1, 2, 3, 4, 5 };
string[] s ={ "a", "b", "c" };
public int this[int index]
{
get
{
return num1s[index];
}
}
public string this[uint index]
{
get
{
return s[index];
}
}
static void Main(string[] args)
{
TestIndex testIndex = new TestIndex();
uint i = 2;
Console.WriteLine(testIndex[i]);
}
}
还需要注意:索引的索引类型不同,而返回值相同,也是正确的。如下示例是正确的:
class TestIndex
{
int[] num1s ={ 1, 2, 3, 4, 5 };
int[] num2s ={ 10, 11, 12, 13, 14, 15 };
public int this[int index]
{
get
{
return num1s[index];
}
}
public int this[uint index]
{
get
{
return num2s[index];
}
}
static void Main(string[] args)
{
TestIndex testIndex = new TestIndex();
uint i = 2;
Console.WriteLine(testIndex[i]);
Console.WriteLine(testIndex[2]);
}
}