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#中索引器是什么