2016-12-14 71 views
3

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

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

你不需要写'GetValue',你知道这个类是一个带有索引器的集合,但是你可能会失去可读性,因为索引器没有名字,所以不要误用它。 –

+2

这是一个*语法糖*,优点是*可读性* –

+0

@DmitryBychenko:可读性不是好处,反之亦然,因为索引器没有名字 –

回答

7

这纯粹是语法上的方便性和可读性/表现。它仍然作为一种方法实施。因此:如果您认为target[0]对您的方案更明显,方便和易读:请使用索引器。