这个问题已经有一个答案在这里:

我想添加一个操作者的一类。我现在有一个 GetValue() 方法,我想换一个 [] 操作员。

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

    public int GetValue(int index)
    {
        return values[index];
    } 
}
有帮助吗?

解决方案

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

其他提示

我相信这是你在找什么:

索引(C#编程指南)

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]);
    }
}

在[]操作者是所谓的索引器。你可以提供索引,采取整数,一串或任何其他类型要用作一个关键。法是直接的,以下相同的原则性访问器。

例如,在你的情况 int 是关键或指数:

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

你还可以添加一组访问使indexer变得阅读和写,而不是只是只读的。

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

  set
  {
    SetValue(index, value);
  }
}

如果你想要索引使用一个不同的类型,你只是改变签字的索引器。

public int this[string index]
...
public int this[int index]
{
    get
    {
        return values[index];
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top