索引器可以像数组一样的使用,在使用的时候需要先定义,定义好之后只需要创建一个对象就可以了。
也就是说你可以使用一个对象进行不同的操作。也就是将一个实例对象划分成更小的部分了。
索引器也可以进行重载
using System;
namespace IndexerApplication
{
class IndexedNames
{
private string[] namelist = new string[size];
static public int size = 10;
//构造函数
public IndexedNames()
{
//初始化字符串数组
for (int i = 0; i < size; i++)
namelist[i] = "N. A.";
}
//定义一个索引器
public string this[int index]
{
//获取值
get
{
string tmp;
if (index >= 0 && index <= size - 1)
{
tmp = namelist[index];
}
else
{
tmp = "";
}
return (tmp);
}
//设置值
set
{
if (index >= 0 && index <= size - 1)
{
namelist[index] = value;
}
}
}
static void Main(string[] args)
{
IndexedNames names = new IndexedNames();
names[0] = "Zara";
names[1] = "Riz";
names[2] = "Nuha";
names[3] = "Asif";
names[4] = "Davinder";
names[5] = "Sunil";
names[6] = "Rubic";
names[9] = "stywen";
for (int i = 0; i < IndexedNames.size; i++)
{
Console.WriteLine(names[i]);
}
Console.ReadKey();
}
}
}
也就是说你可以使用一个对象进行不同的操作。也就是将一个实例对象划分成更小的部分了。
索引器也可以进行重载
using System;
namespace IndexerApplication
{
class IndexedNames
{
private string[] namelist = new string[size];
static public int size = 10;
//构造函数
public IndexedNames()
{
//初始化字符串数组
for (int i = 0; i < size; i++)
namelist[i] = "N. A.";
}
//定义一个索引器
public string this[int index]
{
//获取值
get
{
string tmp;
if (index >= 0 && index <= size - 1)
{
tmp = namelist[index];
}
else
{
tmp = "";
}
return (tmp);
}
//设置值
set
{
if (index >= 0 && index <= size - 1)
{
namelist[index] = value;
}
}
}
static void Main(string[] args)
{
IndexedNames names = new IndexedNames();
names[0] = "Zara";
names[1] = "Riz";
names[2] = "Nuha";
names[3] = "Asif";
names[4] = "Davinder";
names[5] = "Sunil";
names[6] = "Rubic";
names[9] = "stywen";
for (int i = 0; i < IndexedNames.size; i++)
{
Console.WriteLine(names[i]);
}
Console.ReadKey();
}
}
}
本文介绍如何通过定义索引器实现数组操作,包括数组的初始化、元素的获取和设置,以及重载索引器的功能。通过示例代码演示了如何在C#中使用索引器对字符串数组进行灵活的操作。
1150

被折叠的 条评论
为什么被折叠?



