索引器优于对象数组的优点?

Ant*_*ops 2 c# arrays indexer

我读到了MSDN中的索引- 索引器,它解释了我们如何使用像索引一样的对象,就像普通的数组一样.但是,我认为我们可以创建像这样的对象数组

point[] array = new point[100];
Run Code Online (Sandbox Code Playgroud)

那么Indexer对象数组的特殊优势是什么?

Jam*_*mes 5

如果你所追求的只是一个对象的集合,那么索引器对数组没有任何好处.但是,如果您需要存储状态以及集合,那么索引器就会闪耀.

例如,请考虑以下内容

public class Tree
{
    private Branch[] branches = new Branch[100];
    ...

    public string Name { get; set; }

    public Branch this[int i]
    {
        get
        {
            return branches[i];
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Tree拥有一个内部集合,但也有自己的状态.拥有索引器属性允许简单访问底层集合,例如

tree.Name = "Tree";
var branch = tree[0];
Run Code Online (Sandbox Code Playgroud)