c#中索引器是什么_C#中的索引器

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

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值