如何在C#中重载[]运算符

时间:2009-01-08 15:32:03

标签: c# operator-overloading indexer

我想在类中添加一个运算符。我目前有一个GetValue()方法,我想用[]运算符替换。

class A
{
    private List<int> values = new List<int>();

    public int GetValue(int index)
    {
        return values[index];
    } 
}

4 个答案:

答案 0 :(得分:689)

public int this[int key]
{
    get
    {
        return GetValue(key);
    }
    set
    {
        SetValue(key,value);
    }
}

答案 1 :(得分:62)

我相信这就是你要找的东西:

<强> Indexers (C# Programming Guide)

class SampleCollection<T>
{
    private T[] arr = new T[100];
    public T this[int i]
    {
        get
        {
            return arr[i];
        }
        set
        {
            arr[i] = value;
        }
    }
}

// This class shows how client code uses the indexer
class Program
{
    static void Main(string[] args)
    {
        SampleCollection<string> stringCollection = 
            new SampleCollection<string>();
        stringCollection[0] = "Hello, World";
        System.Console.WriteLine(stringCollection[0]);
    }
}

答案 2 :(得分:29)

[]运算符称为索引器。您可以提供带整数,字符串或任何其他要用作键的类型的索引器。语法很简单,遵循与属性访问器相同的原则。

例如,在int是键或索引的情况下:

public int this[int index]
{
  get
  {
     return GetValue(index);
  }
}

您还可以添加一个set访问器,以便索引器变为读写,而不仅仅是只读。

public int this[int index]
{
  get
  {
     return GetValue(index);
  }

  set
  {
    SetValue(index, value);
  }
}

如果要使用其他类型进行索引,只需更改索引器的签名即可。

public int this[string index]
...

答案 3 :(得分:10)

public int this[int index]
{
    get
    {
        return values[index];
    }
}