C#索引器用法 [英] C# Indexer Usage

查看:213
本文介绍了C#索引器用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要使用索引器,我们使用以下格式:

To have an indexer we use the following format:

class ClassName
{
    DataType[] ArrayName = new DataType[Length]; 

    public DataType this[int i]
    {
        get { return ArrayName[i]; }
    }
}

为简单起见,我使用了格式,即使我们也可以使用自定义索引器.根据我的理解,我们将保留一个已编入索引的属性数组.

For the sake of simplicity I used the format, even though we can go for a custom indexer also. According to my understanding, we are keeping a propery array that is indexed.

我的问题是:

  1. 这是模板属性吗?
  2. 使用此索引器可以在何时何地实现高级代码优化?

推荐答案

这与代码优化无关.
您可以在您的类中编写一个方法,使您可以从其拥有的集合中获取项目.

It is not about code optimization.
You could write a method in your class that can get you the item from the collection it holds.

例如

public DataType GetItemByIndex(int i)
{
}

索引器是一种语法糖",使用户可以将实例视为数组或集合.

Indexers are in a way, "syntactic sugar", to let users treat the instance as an array or collection.

这篇关于C#索引器用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆