c#中索引器是什么
An Indexer is a special feature of C# to use an object as an array. If you define an indexer in a class then it will behave like a virtual array. Indexer is also known as smart array in C#. It is not a compulsory or essential part of OOPS.
索引器是C#的一项特殊功能,可以将对象用作数组。 如果在类中定义索引器,则其行为将类似于虚拟数组。 索引器在C#中也称为智能数组。 它不是OOPS的强制性或必要部分。
It is also known as indexed property. It is a class property that allows to access data members using a feature of array.
也称为索引属性 。 它是一个类属性,允许使用数组功能访问数据成员。
We use this object to implement indexer in class.
我们使用该对象在类中实现索引器。
Syntax:
句法:
<Modifier> <return type> this[parameter list]
{
get
{
//write code here
}
set
{
//write code here
}
}
Example
例
using System;
using System.Collections;
namespace ConsoleApplication1
{
class Names
{
static public int len=10;
private string []names = new string[len] ;
public Names()
{
for (int loop = 0; loop < len; loop++)
names[loop] = "N/A";
}
public string this[int ind]
{
get
{
string str;
if (ind >= 0 && ind <= len - 1)
str = names[ind];
else
str = "...";
return str;
}
set
{
if (ind >= 0 && ind <= len - 1)
names[ind]=value;
}
}
}
class Program
{
static void Main()
{
Names names = new Names();
names[0] = "Duggu";
names[1] = "Shaurya";
names[2] = "Akshit";
names[3] = "Shivika";
names[4] = "Veer";
for (int loop = 0; loop < Names.len; loop++)
{
Console.WriteLine(names[loop]);
}
}
}
}
Output
输出量
Duggu
Shaurya
Akshit
Shivika
Veer
N/A
N/A
N/A
N/A
N/A
Important point regarding indexers:
关于索引器的要点:
We use this keyword to implement indexer.
我们使用此关键字来实现索引器。
Indexer can be overloaded.
索引器可能过载。
Indexer cannot be static.
索引器不能是静态的。
Read more: Indexer overloading in C#
: C#中的索引器重载
翻译自: https://www.includehelp.com/dot-net/indexers-in-c-sharp.aspx
c#中索引器是什么