索引器有什么好处?

What are the benefits of an indexer?

有人可以解释一下使用索引器有什么好处吗?

public class MyClass
{
    private List<string> list = new List<string>()

    public string this[int value]
    {
         get 
         {
             return list[value];
         }
     }

     public string GetValue(int value)
     {
          return list[value];
     }
}

使用有什么好处:

MyClass target = new MyClass();
string value = target[0];

关于这个:

MyClass target = new MyClass();
string value = target.GetValue(0);

纯粹是语法方便和可读性/表现力。它仍然作为一种方法来实现。所以:如果您认为 target[0] 对于您的场景更明显、方便和可读:使用索引器。