简体   繁体   English

如何制作锯齿状索引器

[英]How to make jagged indexer

I have seen jagged indexers somewhere and would like to know how to make them work.我在某处看到过锯齿状的索引器,想知道如何使它们工作。

I know I can do the following:我知道我可以做到以下几点:

class foo
{
    public string this[int i1]
    {
        get{ return GetString(i1); }
    }

    public string this[int i1, int i2]
    {
        get{ return GetString(i1) + GetString(i2); }
    }
}

So that:以便:

string s1 = foo[5];
string s2 = foo[12,8];

The question is, how do I define the indexer to do...问题是,我如何定义索引器来做...

string s2 = foo[12][8];

If possible (and otherwise unclear), I would also appreciate the setter definition.如果可能(否则不清楚),我也很欣赏 setter 定义。

foo[12][8] = "qwerty";

Derrick Shepard's answer seems correct, however I had a few notes for you: Derrick Shepard的回答似乎是正确的,但我有一些笔记给你:

With your current methods: 使用您当前的方法:

public string this[int i1]
public string this[int i1, int i2]

foo[12][8] would parse equivalently to (foo[12])[8] ; foo[12][8]会等同地解析(foo[12])[8] ; you'd be getting string foo[12] and then getting it's 9th character. 你会得到string foo[12] ,然后得到它的第9个字符。

If you're willing to change your first method (the indexer with a single argument), you could consider returning an object which would, in turn, provide another indexer. 如果您愿意更改第一个方法(带有单个参数的索引器),您可以考虑返回一个对象,而该对象又提供另一个索引器。

I hope this is what you are looking for:我希望这是你正在寻找的:

class foo
{
    private string[][] collection = new string[2][];

    public string[] this[int index]
    {
        get
        { 
            return collection[index]; 
        }
        set
        {
            collection[index] = value;
        }
    }
}

and then:接着:

string s1 = foo[1][0];
foo[1][0] = s1;

I was happy when I founded this but personally for me is quite confusing because getter and setter are weird.当我创建它时我很高兴,但对我个人来说很困惑,因为 getter 和 setter 很奇怪。 It looks like if collection is 1D array and not jagged.看起来如果集合是一维数组而不是锯齿状。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM