2016-07-07 41 views
-2

什么实际发生在这里:有人可以解释这个C#语法吗?

public decimal[] Coefficients; 
public decimal this[int i] 
{ 
    get { return Coefficients[i]; } 
    set { Coefficients[i] = value; } 
} 

什么是this作为?这是decimal的某种扩展吗?

+5

如果您的类名为MathTest,那么它允许您访问我们的内部系数数组MathTest [i]而不是MathTest.Coefficients [i]。请参阅http://stackoverflow.com/questions/1307354/c-sharp-indexer-usage和http://stackoverflow.com/questions/2185071/real-world-use-cases-for-c-sharp-indexers – ManoDestra

+1

为什么downvotes .. – PreqlSusSpermaOhranitel

+1

不知道。我赞成你。问题对我来说似乎很清楚。也许研究得不是很好,因为它是一个基本的语言语法问题,但仍然是有效的国际海事组织。 – ManoDestra

回答

11

这是一个Indexer

索引器允许像数组一样索引类或结构的实例。索引器类似于属性,但它们的访问器需要参数。从链接MSDN

实施例:

class SampleCollection<T> 
{ 
    // Declare an array to store the data elements. 
    private T[] arr = new T[100]; 

    // Define the indexer, which will allow client code 
    // to use [] notation on the class instance itself. 
    // (See line 2 of code in Main below.)   
    public T this[int i] 
    { 
     get 
     { 
      // This indexer is very simple, and just returns or sets 
      // the corresponding element from the internal array. 
      return arr[i]; 
     } 
     set 
     { 
      arr[i] = value; 
     } 
    } 
} 

// This class shows how client code uses the indexer. 
class Program 
{ 
    static void Main(string[] args) 
    { 
     // Declare an instance of the SampleCollection type. 
     SampleCollection<string> stringCollection = new SampleCollection<string>(); 

     // Use [] notation on the type. 
     stringCollection[0] = "Hello, World"; 
     System.Console.WriteLine(stringCollection[0]); 
    } 
} 
// Output: 
// Hello, World. 
2

你有没有想过如何List<T>myList[i]工作在C#就像一个数组?

答案在你的问题。您发布的语法是编译器转换为名为get_Item(int index)set_Item(int index, decimal value)的属性的语法糖。它在List<T>中用于访问类中使用的内部数组,并返回指定索引处的元素(set或get)。该功能称为Indexer

为了测试自己,尝试创建具有相同签名的方法:

public decimal get_Item(int i) 
{ 
    return 0; 
} 

你会得到一个编译错误:

错误CS0082:类型“MyClass的”已经储备了成员称为 具有相同参数类型的'get_Item'

相关问题