【问题标题】:What are the benefits of an indexer?索引器有什么好处?
【发布时间】:2023-04-07 00:20:01
【问题描述】:

有人能解释一下拥有索引器有什么好处吗?

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

【问题讨论】:

  • 你不需要写GetValue并且你知道这个类是一个带有索引器的集合但是你可能会因为索引器没有名字而失去可读性,所以不要滥用它。
  • 语法糖,优点是可读性
  • @DmitryBychenko:可读性不是好处,相反的可能是正确的,因为索引器没有名称
  • 和@DmitryBychenko说的一模一样,其实只是语法糖
  • 我的经验法则是:如果您的类基本上只是一个集合(或包装一个),请使用索引器。 names[0] 很容易理解为“名字集合中的第一个名字”。如果无法像那样读取呼叫站点,我会避免创建索引器。 YMMV

标签: c# indexer


【解决方案1】:

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

【讨论】: