这个C#代码的含义是什么?如何使用它?

时间:2010-09-22 11:11:02

标签: c#

public int this[int x, int y]
{
   get { return (x + y); }
}

2 个答案:

答案 0 :(得分:20)

它是indexer,接受两个整数。您可以将其视为类似于二维数组,除了结果是在运行中计算而不是存储。

它允许您编写int result = foo[a, b];

答案 1 :(得分:1)

它是一个索引器,该代码可能不正确。您通常会看到:

public int this[int x, int y]
{
    get { return (x * ColSize + y); }
}

class TheMatrix<T>
{
    private int _rows, _cols;
    private T[] _data;
    public TheMatrix(int rows, int cols)
    {
        _rows = rows;
        _cols = cols;
        _data = new T[_rows * _cols];
    }

    T this[int r, int c]
    {
        get { return _data[r * _cols + c]; }
        set { _data[r * _cols + c] = value; }
    }
}