我在某个地方看到了锯齿状的索引器,想知道如何使它们工作。

我知道我可以执行以下操作:

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

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


以便:

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


问题是,如何定义索引器来执行...

string s2 = foo[12][8];


如果可能(否则不清楚),我也将欣赏二传手的定义。

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

最佳答案

德里克·谢泼德(Derrick Shepard)的回答似乎正确,但是我为您提供了一些注意事项:

使用您当前的方法:

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


foo[12][8]将等同解析为(foo[12])[8];您将得到string foo[12],然后得到第9个字符。

如果您愿意更改第一个方法(带有单个参数的索引器),则可以考虑返回一个对象,该对象将提供另一个索引器。

10-07 19:30
查看更多