//简单实例
public class MyClass
{
private string[] myArray = new string[5];
// 索引器
public string this[int index]
{
get
{
return myArray[index];
}
set
{
myArray[index] = value;
}
}
}
public class Program
{
static void Main(string[] args)
{
MyClass myObject = new MyClass();
// 设置索引器的值
myObject[0] = "Hello";
myObject[1] = "World";
// 获取索引器的值
Console.WriteLine(myObject[0]); // 输出: Hello
Console.WriteLine(myObject[1]); // 输出: World
}
}
//多维数组实例
public class MyMatrix
{
private int[,] matrix = new int[3, 3];
// 索引器
public int this[string row, string column]
{
get
{
int rowIndex = GetRowIndex(row);
int columnIndex = GetColumnIndex(column);
return matrix[rowIndex, columnIndex];
}
set
{
int rowIndex = GetRowIndex(row);
int columnIndex = GetColumnIndex(column);
matrix[rowIndex, columnIndex] = value;
}
}
private int GetRowIndex(string row)
{
// 在此处根据行名返回相应的行索引
// 这里只是一个示例,您需要根据实际需求进行实现
if (row == "A")
return 0;
else if (row == "B")
return 1;
else if (row == "C")
return 2;
else
throw new ArgumentException("Invalid row name");
}
private int GetColumnIndex(string column)
{
// 在此处根据列名返回相应的列索引
// 这里只是一个示例,您需要根据实际需求进行实现
if (column == "X")
return 0;
else if (column == "Y")
return 1;
else if (column == "Z")
return 2;
else
throw new ArgumentException("Invalid column name");
}
}
public class Program
{
static void Main(string[] args)
{
MyMatrix myMatrix = new MyMatrix();
// 设置索引器的值
myMatrix["A", "X"] = 1;
myMatrix["B", "Y"] = 2;
// 获取索引器的值
Console.WriteLine(myMatrix["A", "X"]); // 输出: 1
Console.WriteLine(myMatrix["B", "Y"]); // 输出: 2
}
}